Thursday, February 12, 2015

Implementation of Queue using Linked List

AIM:
          To write a C program to implement queue using linked list

ALGORITHM:
            Step 1: Start the program.
            Step 2: For queue insertion operation, check for queue overflow
Step 3: If R>=N then print queue overflow else increment rear pointer and insert  
            the element.
Step 4: For queue deletion operation, check for underflow of the queue.
Step 5: If F=0 then print queue underflow else delete the element and increment 
            the front pointer
Step 6: Stop the program.

PROGRAM
#include<stdio.h >
#include<conio.h >
#include<alloc.h >
struct queue
{
int data;
struct queue *next;
};
struct queue *addq(struct queue *front);
struct queue *delq(struct queue *front);
void main()
{
struct queue *front;
int reply,option,data;
clrscr();
front=NULL;
do
{
printf("\n1.addq");
printf("\n2.delq");
printf("\n3.exit");
printf("\nSelect the option");
scanf("%d",&option);

switch(option)
{
case 1 : //addq
front=addq(front);
printf("\n The element is added into the queue");
break;
case 2 : //delq
front=delq(front);
break;
case 3 : exit(0);
}
}while(1);
}
struct queue *addq(struct queue *front)
{
struct queue *c,*r;
//create new node
c=(struct queue*)malloc(sizeof(struct queue));
if(c==NULL)
{
printf("Insufficient memory");
return(front);
}
//read an insert value from console
printf("\nEnter data");
scanf("%d",&c->data);
c->next=NULL;
if(front==NULL)
{
front=c;
}
else
{
//insert new node after last node
r=front;
while(r->next!=NULL)
{
r=r->next;
}}
return(front);
}
struct queue *delq(struct queue *front)
{
struct queue *c;
if(front==NULL)
{
printf("Queue is empty");
return(front);
}
//print the content of first node
printf("Deleted data:%d",front->data);
//delete first node
c=front;
front=front->next;
free(c);
return(front);
}

OUTPUT
1.addq
2.delq
3.exit
Select the option 1
Enter data 8
1.addq
2.delq
3.exit
Select the option 1
Enter data 5
1.addq
2.delq
3.exit
Select the option 1
Enter data 9
1.addq
2.delq
3.exit
Select the option 1
Enter data 1
1.addq
2.delq
3.exit
Select the option 2
Deleted data: 8
1.addq
2.delq
3.exit
Select the option 3


RESULT: Thus a C program is written to implement queue using linked list and

                   executed successfully

No comments:

Post a Comment