Saturday 18 February 2012

C program to implement a queue using linked list



#include<stdio.h>
void enq();
void deq();
void display();
main()
{
int n;
printf("\tMENU\n1.ENQUEUE\n2.DEQUEUE\n3.DISPLAY\n4.EXIT\n");
do
{
printf("\nEnter your choice\n");
scanf("%d",&n);
switch(n)
{
case 1:
enq();
break;
case 2:
deq();
break;
case 3:
display();
break;
case 4:
break;
default:
printf("Invalid choice\n");
break;
}
}
while(n!=4);
}

typedef struct node
{
int data;
struct node *link;
}n;
n *front=NULL;
n *rear=NULL;

void enq()
{
int item;
n *temp;
printf("Enter the item\n");
scanf("%d",&item);
temp=(n*)malloc(sizeof(n));
temp->data=item;
temp->link=NULL;
if(rear==NULL)
{
front=temp;
rear=temp;
}
else
{
rear->link=temp;
rear=temp;
}
}

void deq()
{
int item;
if(front==NULL)
printf("Queue is empty\n");
else
{
item=front->data;
printf("The element deleted = %d\n",item);
}
if(front==rear)
{
front=NULL;
rear=NULL;
}
else
front=front->link;
}

void display()
{
n *ptr;
if(front==NULL)
printf("Queue is empty\n");
else
{
ptr=front;
printf("The elements of the queue are :");
while(ptr!=NULL)
{
printf("%d\t",ptr->data);
ptr=ptr->link;
}
}
}



You Like It!? Then kindly share with your Friends.
Comments
4 Comments

4 comments:

Post a Comment