C program to implement QUEUE with its operation
Queue & Its Operation
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at both its ends. One end is always used to insert data (enqueue) and the other is used to remove data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first will be accessed first.
A real-world example of queue can be a single-lane one-way road, where the vehicle enters first, exits first. More real-world examples can be seen as queues at the ticket windows and bus-stops.
Enqueue Operation
Queues maintain two data pointers, front and rear. Therefore, its operations are comparatively difficult to implement than that of stacks.
The following steps should be taken to enqueue (insert) data into a queue −
- Step 1 − Check if the queue is full.
- Step 2 − If the queue is full, produce overflow error and exit.
- Step 3 − If the queue is not full, increment rear pointer to point the next empty space.
- Step 4 − Add data element to the queue location, where the rear is pointing.
- Step 5 − return success.
Algorithm Of Enqueue Operation:
Procedure: ENQUEUE(Q, F, R, N, Y)
1. [Overflow]
IF R>=N
Then write("Overflow")
Return
2. [Increment Rear pointer]
R<-R+1
3. [Insert Element]
Q[R]<-Y
4. [Is FRONT pointer properly set]
IF F=0
Then F<-1
Return
Dequeue Operation
Accessing data from the queue is a process of two tasks − access the data where front is pointing and remove the data after access. The following steps are taken to perform dequeue operation −
- Step 1 − Check if the queue is empty.
- Step 2 − If the queue is empty, produce underflow error and exit.
- Step 3 − If the queue is not empty, access the data where front is pointing.
- Step 4 − Increment front pointer to point to the next available data element.
- Step 5 − Return success.
Algorithm Of Dequeue Operation:
Procedure: DEQUEUE(Q, F, R)
1. [Underflow]
IF F=0
Then write("Underflow")
Return 0
2. [Decrement element]
Y<-Q[F]
3. [Queue Empty?]
IF F=R
Then F<-R<-0
Else F<-F+1
4. [Return Element]
Return Y
#include <stdio.h>
#include <conio.h>
int i,f=0,r=0,x,c,s[100],n;
void insert();
void del();
void display();
void main()
{
clrscr();
printf("\nEnter the size of queue:");
scanf("%d",&n);
while(1)
{
printf("\n1).Insert 2).Delete 3).Display 4).Exit\n");
printf("Enter your choice: ");
scanf("%d",&c);
switch(c)
{
case 1:
insert();
break;
case 2:
del();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Enter the valid choice");
}
}
}
void insert()
{
if(r>=n)
{
printf("\nQueue is overflow");
}
else
{
r++;
printf("\nEnter the value:");
scanf("%d",&x);
s[r]=x;
if(f==0)
{
f=1;
}
}
}
void del()
{
if(f<=-1)
{
printf("\nQueue is underflow");
}
else
{
printf("Deleted element : %d",s[f]);
s[f]=NULL;
if(f==r)
{
f=r=-1;
}
else
{
f++;
}
}
}
void display()
{
printf("Elements in queue: ");
for(i=1;i<=r;i++)
{
printf("\n%d",s[i]);
}
}
Comments
Post a Comment