Count Linked List Node problem GFG

Given a singly linked list. The task is to find the length of the linked list, where length is defined as the number of nodes in the linked list.


Examples :


Input: LinkedList : 1->2->3->4->5


Output: 5

Explanation: Count of nodes in the linked list is 5, which is its length.

Input: LinkedList : 2->4->6->7->5->1->0

 

Output: 7

Explanation: Count of nodes in the linked list is 7. Hence, the output is 7.

Expected Time Complexity: O(n)

Expected Auxilliary Space: O(1)



Solution :


//{ Driver Code Starts

import java.io.*;

import java.util.*;


class Node {

    int data;

    Node next;


    Node(int a) {

        data = a;

        next = null;

    }

}



// } Driver Code Ends

/*Complete the function below*/

/*

class Node{

    int data;

    Node next;

    Node(int a){  data = a; next = null; }

}*/


class Solution {

    // Function to count nodes of a linked list.

    public int getCount(Node head) {

        // code here

        

        int count = 0;

        Node tail = head;

        

        while (tail != null) { // Traverse the list

            count++;

            tail = tail.next; // Move to next node

        }

        

        return count; // Return final count

    }

}


//{ Driver Code Starts.


class LinkedList {


    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int t = Integer.parseInt(br.readLine());

        while (t-- > 0) {

            ArrayList<Integer> arr = new ArrayList<>();

            String input = br.readLine();

            StringTokenizer st = new StringTokenizer(input);

            while (st.hasMoreTokens()) {

                arr.add(Integer.parseInt(st.nextToken()));

            }

            Node head = new Node(arr.get(0));

            Node tail = head;

            for (int i = 1; i < arr.size(); ++i) {

                tail.next = new Node(arr.get(i));

                tail = tail.next;

            }

            Solution ob = new Solution();

            System.out.println(ob.getCount(head));

        

System.out.println("~");

}

    }

}


// } Driver Code Ends 

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence