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}

**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.

**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..!

### Like this:

Like Loading...

*Related*

## Published by Prajwal Zade PZ

Every programmer is an good author!
View all posts by Prajwal Zade PZ