Friday, September 5, 2008

C program to show all operations on singly linked list

#include < stdio.h>
#include < process.h>
#include < malloc.h>


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

typedef struct node *NODE;


NODE getnode()
{
NODE x;

x=(NODE) malloc( sizeof(struct node));

if(x==NULL)
{
printf(" Out of memory\n");
exit(0);
}

return x;
}

void freenode( NODE x)
{
free(x);
}



NODE insert_front(int item,NODE first)
{
NODE temp;

temp=getnode();

temp->info=item;
temp->link=first;

return temp;
}

NODE insert_rear(int item,NODE first)
{
NODE temp;
NODE cur;

temp=getnode();

temp->info=item;
temp->link=NULL;

if(first==NULL)
return temp;

cur=first;

while(cur->link!=NULL)
{
cur=cur->link;
}

cur->link=temp;

return first;
}

NODE delete_front(NODE first)
{
NODE temp;
if(first== NULL)
{
printf(" list empty");
return first;
}

temp=first;
first=first->link;

printf(" Item deleted=%d\n",temp->info);
freenode(temp);

return first;
}

NODE delete_rear(NODE first)
{
if(first==NULL)
{
printf(" list empty\n");
return first;
}

if(first->link==NULL)
{
printf(" Item deleted=%d\n",first->info);
freenode(first);
first=NULL;
return first;
}
NODE prev=NULL;
NODE cur=first;

while(cur->link!=NULL)
{
prev=cur;
cur=cur->link;
}

printf(" Item deleted=%d\n",cur->info);
freenode(cur);

prev->link=NULL;

return first;
}

void display(NODE first)
{
if(first==NULL)
{
printf(" list empty\n");
return;
}

printf(" The contents of list\n");

NODE temp=first;

while(temp!=NULL)
{
printf("%d ",temp->info);
temp=temp->link;
}

}


void main()
{
NODE first=NULL;
int choice,item,item_deleted;

for(;;)
{
printf(" 1.insert front\n2insert rear\n3delete front\n4.delete rear\n5.display");
printf(" 6.exit\n");

printf(" enter the choice\n");
scanf(" %d",&choice);

switch(choice)
{
case 1:
printf(" Enter the item to be inserted\n");
scanf(" %d",&item);
first=insert_front(item,first);
break;

case 2:
printf(" Enter the item to be inserted\n");
scanf(" %d",&item);
first=insert_rear(item,first);
break;

case 3:
delete_front(first);
break;

case 4:
delete_rear(first);
break;

case 5:
display(first);
break;

default:
exit(0);

}
}
}

0 comments: