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 <= 10^{5} 1 <= value <= 10^{3}

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.

## Leave a Reply