Counting number of Nodes in Singly Linked List



Counting number of Nodes in Linked List :

We know the logic for traversing through the linked list in C Programming. [See Dry Run]

Function for counting the singly linked nodes is very similar to display(), Only difference is that instead of printing data we are incrementing length variable.

Two Ways of Counting the Number of Nodes :

We are counting the number of nodes using two ways – Using Non Recursion and Using Recursion.

Program : Way 1 [ Does not Returning Value]

void count()
{
    struct node *temp;
    int length = 0;
    temp = start;
    while(temp!=NULL)
    {
        length++;
        temp=temp->next;
    }
printf("nLength of Linked List : %d",length);
}

Program : Way 2 [Returning Value]

int count()
{
    struct node *temp = start;
    int length = 0;
    while(temp!=NULL)
    {
        length++;
        temp=temp->next;
    }
return(length);
}

Program : Way 3 [ Recursive Program to Count Number of Nodes in Linked List ]

int count(node *temp)
{
 if(temp == NULL)
     return(0);
 return(1 + count(temp->next));
}

Explanation of Recursive Function :

Consider the [this linked list] – Recursive function call for linked list is as follow –


Recursive-function-for-counting-Linked-List-Nodes