Sunday, 6 May 2012

Inserting a node in a Linked List in C


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


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


node *start = NULL;


int main()
{
void add(int);
int disp();
void del();
int value,count=0;
char choice;

while(1)
{
printf("Do you want to insert a node? (Y/N) \n");
scanf("%c",&choice);
if(choice=='y'||choice=='Y')
{
printf("Enter the info of the node:\n");
scanf("%d",&value);
add(value);
fflush(stdin);
}
else
{
break;
}
}
printf("The linked list is :\n");
count=disp();
printf("Number of elements present in the linked list = %d\n",count);
del();
getch();
main();//for repeating the program ... i have no idea if calling main() at the end is a good idea or not. we'll find out!!!
return 0;
}


void add(int data)
{
node *newptr;
newptr=(node*)malloc(sizeof(node));
newptr->info=data;
newptr->link=start;
start=newptr;
}


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


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


No comments:

Post a Comment