Friday, September 5, 2008

C program to demostrate Queue using singly linked list

#include < stdio.h >
#include < malloc.h >
#include < process.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_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;
}





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;

for(;;)
{
printf(" 1.insert rear\n2.delete front\n3.display\n4.exit\n");
printf(" Enter choice\n");
scanf(" %d", &choice);

switch(choice)
{
case 1:
printf("Item:");
scanf("%d",&item);
first=insert_rear(item,first);
break;
case 2:
first=delete_front(first);
break;
case 3:
display(first);
break;
default:
exit(0);
}
}
}

0 comments: