A Queue is a linear data structure. It is a list in which all insertions to the queue are performed at one end and all the deletions are performed at the other end. The element in the queue are processed in the same order in which they were received. Hence it is called a First In First Out(FIFO) list.
Applications of Queue
- Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
- In real life, Call Center phone systems will use Queues, to hold people calling them in an order, until a service representative is free.
- Handling of interrupts in real-time systems.
Basic operation
Enqueue Operation
Queues maintain two data pointers, front and rear.
The steps should for 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.
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.
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.
Array Implementation Of Queue
#include <stdio.h>
#define MAX 50
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1: insert();
break;
case 2: delete();
break;
case 3: display();
break;
case 4: exit(1);
default: printf("Wrong choice \n");
} /*End of switch*/
} /*End of while*/
} /*End of main()*/
insert()
{
int add_item;
if (rear == MAX - 1)
{
printf("Queue Overflow \n");
}
else
{
if (front == - 1)
{
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
}
} /*End of insert()*/
delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /*End of delete() */
display()
{
int i;
if (front == - 1)
{
printf("Queue is empty \n");
}
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
{
printf("%d ", queue_array[i]);
printf("\n");
}
}
}
Analysis of Queue
- Enqueue : O(1)
- Dequeue : O(1)
- Size : O(1)
Please go through video:
https://www.youtube.com/watch?v=okr-XE8yTO8