Skip to main content

Count Linked List Nodes

Problem​

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:​

Example 1:

Input:
LinkedList: 1->2->3->4->5
Output: 5
Explanation: Count of nodes in the linked list is 5, which is its length.

Example 2:

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.

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

  • Expected Time Complexity: O(N)O(N)
  • Expected Auxiliary Space: O(1)O(1)

Constraints:​

  • 1<=N<=1051<=N<=10^5
  • 1<=value<=1031<=value<=10^3

Solution​

Python​

def getCount(self, head_node):
temp = head_node
count = 0
while temp is not None:
count+=1
temp = temp.next
return count

Java​

public static int getCount(Node head) {
Node temp = head;
int count = 0;
while(temp!=null) {
count++;
temp = temp.next;
}
return count;
}

C++​

int getCount(struct Node* head){
struct Node* temp = head;
int count = 0;
while (temp != NULL) {
count++;
temp = temp->next;
}
return count;
}

C​

int getCount(struct Node* head) {
struct Node* temp = head;
int count = 0;
while (temp != NULL) {
count++;
temp = temp->next;
}
return count;
}
  • Time Complexity: O(N)O(N)
  • Auxiliary Space: O(1)O(1)