Count the node of linked list in Java

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.

Input:
The first line of input contains the number of test cases T. For each test case, the first line of input contains the number of nodes N, to be inserted into the linked list and the next line contains data of N nodes.

Output:
There will be a single line of output for each test case, which contains the length of the linked list.

User Task:
Your task is to complete the given function getCount(), which takes a head reference as an argument and should return the length of the linked list.

Constraints:
1 <= T <= 100
1 <= N <= 105
1 <= value <= 103

Example:
Input:

2
5
1 2 3 4 5
7
2 4 6 7 5 1 0
Output:
5
7

Explanation:
Testcase 1: Count of nodes in the linked list is 5, which is its length.
Testcase 2: Count of nodes in the linked list is 7. Hence, the output is 7.

Understand it in graphical way:

Code:

public static int getCount(Node head)
{

    int count = 1;
    if(head == null)
    return 0;
while(head.next != null) {
    count++;
    head = head.next;
}
return count;
}

Recursive approach to count the node of linked list:

    public static int getCount(Node head)
{
     if(head == null)
        return 0;
     return 1 + getCount(head.next);
}

Hope you all understand the concept of how to count the node of linked list.

Thank you..!



Categories: HackerRank Questions, Interview, JAVA

Tags: , , , , , , , , , , , , , ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: