In this blog post we will learn how to count the number of nodes in a linked list using c/ c++ program. to count linked list nodes we have to traverse the linked list from head to tail. It is generally asked in programming job interview.

write a c program to count the number of linked list nodes.

For example in the below figure ,there are 5 nodes in the linked list.

how to count the number of nodes in a linked list

Sample code for how to count the number of nodes in a linked list 

C/C++ program:- ( iterative method)

C/C++ program:- ( recursive method):-

How recursive method works here?

  • In the count_r (list *head,int count) function, we call count_r again and again if there is next node available.
  • During each recursive call of count_r function , we are incrementing count variable and passing count in function argument.
  • Recursion ends when condition head==NULL becomes true, at this time we are returning count.

Ref:

https://stackoverflow.com/questions/22086128/counting-all-the-nodes-in-a-linked-list




Related Contents to follow