Saturday, 28 April 2012

C Program to Create a Linked List Dynamically and Count the Number of Elements



#include<stdio.h>
#include<conio.h>

typedef struct nodetype
{
 int info;
 struct nodetype *link;
}node;

node *start=NULL;

void main()
{
 void add(int);
 void disp();
 int showcount();
 void del();
 int value,count=0;
 char choice;
 
 clrscr();
 while(1)
 {
  printf("\nDo you want to insert the node? ( Y/N )\n\n:");
  scanf("%c",&choice);
  if(choice=='y'||choice=='Y')
  {
   printf("Enter the 'info':\n");
   scanf("%d",&value);
   add(value);
   fflush(stdin);
  }
  else
  {
   break;
  }
 }
 printf("\nThe Linked List is: \n\n");
 disp();
 count=showcount();
 printf("Number of elements present in the list: %d\n",count);
 del();
 getch();
}

void add(int data)
{
 node *newptr=NULL;
 node *ptr;

 newptr = (node*)malloc(sizeof(node));
 newptr->info=data;
 newptr->link=NULL;
 start=newptr;
 if(start==NULL)
 {
  start=newptr;
 }
 else
 {
  ptr=start;
 }
 while(ptr->link!=NULL)
 {
  ptr=ptr->link;
 }
 ptr->link=newptr;
}

void disp()
{
 node *ptr = start;
 printf("->");
 while(ptr)
 {
  printf("%d->",ptr->info);
  ptr=ptr->link;
 }
 printf("NULL\n");
}

int showcount()
{
 int ncount=0;
 node *ptr=start;
 while(ptr)
 {
  ncount++;
  ptr=ptr->link; // There's a small bug here ;)
 }
 return(ncount);
}

void del()
{
 node *ptr;
 while(start!=NULL)
 {
  ptr=start;
  start=start->link;
  free(ptr);
 }
}

No comments:

Post a Comment