Pages

Thursday, 2 February 2017

Link List Count Function

NIELIT O Level Solved Paper
January 2016

Q 9 B. Define the structure of a node of a singly linked list and use it to write a function to count the
number of nodes in a singly linked list. The function should accept a pointer to the first node of
the list and it should return the number of nodes in the list.

Solution : 

/*   ************************************************
           Girfa : Student Help
           Counting node in link list
           for more program visit : http://girfahelp.blogspot.com/p/c-language-assignment.html
     *************************************************/

typedef struct n
{
 int data;
 struct n *next;
}node;
/* Function Prototype */
node *start=0; /* Global Variable point first node*/
int count();
void add(int);
void disp();
#include<stdio.h>
#include<conio.h>
void main()
{
     int opt,n;

     do
     {
           clrscr();
           printf("\n1. Add\n2. Count\n3. Display\n0. Exit\nEnter your choice>> ");
           scanf("%d",&opt);
           switch(opt)
           {
                case 1:
                printf("Enter  number to add in list>> ");
                scanf("%d",&n);
                add(n);
                break;
                case 2:
                     printf("\nTotal %d node in link list>> ",count(start));
                     getch();
                     break;
                case 3:
                     disp();
                     getch();
                case 0:
                     break;
                default:
                     printf("Invalid Choice");
                     getch();
           }
       }while(opt!=0);

}
int count()
{
     node *pt;
     int i=0;
     for(pt=start;pt!=NULL;pt=pt->next)
           i++;
     return i;
}
void add(int n)
{
           node *nw=(node*) malloc(sizeof(node));
           nw->next=NULL;
           nw->data=n;
           if(start==NULL)
                start=nw;
           else
           {
                nw->next=start;
                start=nw;
           }


}
void disp()
{
     node *pt;
     for(pt=start;pt!='\0';pt=pt->next)
           printf("[%d]",pt->data);

}

No comments:

Post a Comment