Write an algorithm to find length of a simple link list

Question: Write an algorithm to find length of a simple link list.

Write an algorithm to find length of a simple link list

Write a function to count the number of nodes in a given singly link list:
Write a function to count the number of nodes

Example: The function should return 5 for linked list 1->3->1->2->1.

Iterative Solution
1) Initialize count as 0 
2) Initialize a node pointer, current = head.
3) Do following while current is not NULL
     a) current = current -> next
     b) count++;
4) Return count 
Following are implementations of above algorithm to find count of nodes:
C++:
Download Code: Click Here


C:
Download Code: Click Here

Java:
Download Code: Click Here

Python:
Download Code: Click Here

C#:
Download Code: Click Here
Output:
count of nodes is 5
Recursive Solution
int getCount(head)
1) If head is NULL, return 0.
2) Else return 1 + getCount(head->next) 
Following are implementations of above algorithm to find count of nodes.

C/C++:
Download Code: Click Here

Java:
Download Code: Click Here

Python:
Download Code: Click Here
C#:
Download Code: Click Here

Output:
count of nodes is 5

Download the Android app to get all Government Job Notifications on your Mobile.
Download Now
Important: Please always Check and Confirm the above details with the official Advertisement / Notification.
Previous Post Next Post