Count Number of Node in Linked List


In order to count number of nodes in linked list we have to traverse from first node to last node in the list.

Algorithm to Count Number of Node in Linked List


Step 1: Count = 0
           SAVE = FIRST
Step 2: Repeat step 3 while SAVE ≠ NULL
Step 3: Count= Count + 1
           SAVE=SAVE->LINK
Step 4: Return Count


     

Program to Count Number of Node in Linked List


#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
      int info;
      struct node *link;
};
struct node *FIRST;
void createlist()
{
      char ch;
      printf("Enter n for break:\n");
      scanf("%c",&ch);
      while(ch!='n')
      {
      struct node *NEW_NODE,*SAVE;int x;
      NEW_NODE=(struct node *)malloc(sizeof(struct node));
      printf("Enter Data:");
      scanf("%d",&x);
      NEW_NODE->info=x;
      if(FIRST==NULL)
      {
         NEW_NODE->link=NULL;
         FIRST=NEW_NODE;
      }
      else
      {
         SAVE=FIRST;
         while(SAVE->link!=NULL)
         {
            SAVE=SAVE->link;
         }
         SAVE->link=NEW_NODE;
         NEW_NODE->link=NULL;
      }
      fflush(stdin);
      printf("Enter n for break:\n");
      scanf("%c",&ch);
   }
}
void countnode()
{
     struct node *SAVE;
     int count=0;
     SAVE=FIRST;
     while(SAVE!=NULL)
     {
       count++;
       SAVE=SAVE->link;
     }
     printf("There are %d nodes in list",count);
}
void display()
{
      struct node *SAVE;
      if(FIRST==NULL)
      {
         printf("Linked List is empty\n");
         return;
      }
      printf("elements are:\n");
      SAVE=FIRST;
      while(SAVE!=NULL)
      {
         if(SAVE->link==NULL)
         printf("|%d|",SAVE->info);
         else
         printf("|%d|->",SAVE->info);
         SAVE=SAVE->link;
      }
      printf("\n");
      return;
}
void main()
{
      clrscr();
      FIRST=NULL;
      createlist();
      display();
      countnode();
      getch();
}

Download Projects


Download Programs