Saturday, September 4, 2010

C Program to count the number of nodes in the singly linked list

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
      int data;
      struct node *link;
};
void append(struct node**,int);
void display(struct node*);
int count(struct node *);
void main()
{
     struct node *head;


     clrscr();
     head=NULL;
     append(&head,5);
     append(&head,6);
     append(&head,7);
     append(&head,8);
     display(head);

     printf("\n No of nodes in the list is %d",count(head));

     getch();
}
void append(struct node **q,int num)
{
     struct node *temp,*r;
     temp=*q;

     if(temp==NULL)  /* If list is empty , create first node */
     {
            temp=(struct node*)malloc(sizeof(struct node));
            temp->data=num;
            temp->link=NULL;
            *q=temp;
     }
     else
     {
          temp=*q;
          while(temp->link !=NULL)
          temp=temp->link;

          r=(struct node*)malloc(sizeof(struct node));
          r->data=num;
          r->link=NULL;
          temp->link=r;
     }
}
void display(struct node *start)
{
     printf("\n");
     printf(" The Linked List is :\n");
     /* Traverse the entire linked list */
     while(start != NULL)
     {
          printf("   %d",start->data);
          start=start->link;
     }

}

int count(struct node *q)
{
     int c=0;
     /* traverse the entire linked list */
     while(q!=NULL)
     {
        q=q->link;
        c++;
     }
     return c;
}

4 comments:

  1. @aryan rocks on feet...
    sry for inconvenience....

    but i hav checked it again....

    its working.....!!!!

    u hav done some mistake .... i guess..!!!

    ReplyDelete
  2. it's absolutely right!!!!!thanks a lot!!!!!

    ReplyDelete
  3. @MOUBANI BASU

    ur welcome :-) ..............!!!

    ReplyDelete