Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Queue Data Structure

A queue is a useful data structure in programming. It is similar to the ticket


queue outside a cinema hall, where the first person entering the queue is
the first person who gets the ticket.

Queue follows the First In First Out (FIFO) rule - the item that goes in first
is the item that comes out first.

Fig: FIFO Representation of Queue

In the above image, since 1 was kept in the queue before 2, it is the first to
be removed from the queue as well. It follows the FIFO rule.
In programming terms, putting items in the queue is called enqueue, and
removing items from the queue is called dequeue.

 Queue is considered as linear data structure, hence it can be


represented using the array. It is also known as static representation
of queue.
 Here two pointers will work: front and rear
 Front will point to the first element while rear will point to the last
element.
 Consider an int arr[5], initially queue is empty, hence front and rear
both will point to the -1.
 If front and rear both are at -1, then queue is empty.
Basic Operations of Queue
A queue is an object (an abstract data structure - ADT) that allows the
following operations:

 Create(): Creates and initializes new queue that is empty. It does not
require any parameter and returns an empty queue.
 Enqueue(item): Add an element to the end (rear) of the queue
 Dequeue(): Remove an element from the front of the queue
 IsEmpty(): Check if the queue is empty or not. It returns Boolean
value.
 IsFull(): Check if the queue is full or not. It returns Boolean value.
 Peek(): Get the value of the front of the queue without removing it.
 Size(): Returns total number of elements present in the queue.

Working of Queue
Queue operations work as follows:

 two pointers FRONT and REAR

 FRONT track the first element of the queue


 REAR track the last element of the queue
 initially, set value of FRONT and REAR to -1
Enqueue Operation

 check if the queue is full


 for the first element, set the value of FRONT to 0
 increase the REAR index by 1
 add the new element in the position pointed to by REAR

Algorithm:

1. if rear = size-1 then write “Queue is full”


2. rear = rear + 1
3. queue[rear] = X
4. if front = -1 then front = 0
Dequeue Operation

 check if the queue is empty


 return the value pointed by FRONT
 increase the FRONT index by 1
 for the last element, reset the values of FRONT and REAR to -1
Algorithm:

1. if front = -1 then write “Queue is empty”


2. return queue[front]
3. if front = rear then front = -1, rear = -1, else front = front + 1

Enqueue and Dequeue Operations


Parameter Stack Queue

Element are added and deleted Element are added and deleted
Operation End from same end. from different end.
Single pointer is used to point top Two pointers are used to point
Pointer of stack. front and rear ends.
It follows LIFO (Last In First Out) It follows FIFO (First In First Out)
Order order. order.
Stack operations are push and Queue operations are enqueue
Operation names pop. and dequeue.
The visualization of stack is of The visualization of stack is of
Visualizations vertical collection. horizontal collection.
Books kept one above other in Queue for booking tickets at
Examples shelf. theatre.

Queue Implementations in C
// Queue implementation in C

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define SIZE 5

void enQueue(int);
void deQueue();
void display();

int items[SIZE], front = -1, rear = -1;

int main()
{
int ch, x;
while(1)
{
printf("\n1. Insert");
printf("\n2. Delete");
printf("\n3. Display");
printf("\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1:
printf("Enter the element: ");
scanf("%d", &x);
enQueue(x);
break;
case 2:
deQueue();
break;
case 3:
display();
break;
case 4:
exit(0);
}
return 0;
}

void enQueue(int value)


{
if (rear == SIZE - 1)
printf("\nQueue is Full!!");
else {
if (front == -1)
front = 0;
rear++;
items[rear] = value;
printf("\nInserted -> %d", value);
}
}

void deQueue()
{
if (front == -1)
printf("\nQueue is Empty!!");
else {
printf("\nDeleted : %d", items[front]);
front++;
if (front > rear)
front = rear = -1;
}
}

// Function to print the queue


void display()
{
if (rear == -1)
printf("\nQueue is Empty!!!");
else {
int i;
printf("\nQueue elements are:\n");
for (i = front; i <= rear; i++)
printf("%d ", items[i]);
}
printf("\n");
}
Limitations of Queue
As you can see in the image below, after a bit of enqueuing and dequeuing,
the size of the queue has been reduced.

Fig: Limitation of a queue


And we can only add indexes 0 and 1 only when the queue is reset (when
all the elements have been dequeued).

After REAR reaches the last index, if we can store extra elements in the
empty spaces (0 and 1), we can make use of the empty spaces. This is
implemented by a modified queue called the circular queue.

Applications of Queue
 CPU scheduling, Disk Scheduling

 When data is transferred asynchronously between two processes.


The queue is used for synchronization. For example: IO Buffers,
pipes, file IO, etc

 Handling of interrupts in real-time systems.

 Call Center phone systems use Queues to hold people calling them
in order.

Types of Queues
A queue is a useful data structure in programming. It is similar to the ticket
queue outside a cinema hall, where the first person entering the queue is
the first person who gets the ticket.
There are four different types of queues:

 Simple Queue

 Circular Queue

 Priority Queue

Simple Queue
In a simple queue, insertion takes place at the rear and removal occurs at
the front. It strictly follows the FIFO (First in First out) rule.

Simple Queue Representation


To learn more, visit Queue Data Structure.
Circular Queue
In a circular queue, the last element points to the first element making a
circular link.

Circular Queue
Representation
The main advantage of a circular queue over a simple queue is better
memory utilization. If the last position is full and the first position is empty,
we can insert an element in the first position. This action is not possible in a
simple queue.

Priority Queue
A priority queue is a special type of queue in which each element is
associated with a priority and is served according to its priority. If elements
with the same priority occur, they are served according to their order in the
queue.

Fig: Priority Queue Representation


Insertion occurs based on the arrival of the values and removal occurs
based on priority.

Circular Queue Data Structure


Circular queue is a linear data structure in which the operations are carried
out on the basis of FIFO (First In First Out) principle and last position is
connected back to the first position to make a circle.
A circular queue is the extended version of a regular queue where the last
element is connected to the first element. Thus, forming a circle-like
structure.

Fig: Circular queue representation


The circular queue solves the major limitation of the normal queue. In a
normal queue, after a bit of insertion and deletion, there will be non-usable
empty space.

Fig: Limitation of the regular Queue

Here, indexes 0 and 1 can only be used after resetting the queue (deletion
of all elements). This reduces the actual size of the queue.
How Circular Queue Works
Circular Queue works by the process of circular increment i.e. when we try
to increment the pointer and we reach the end of the queue, we start from
the beginning of the queue.

Here, the circular increment is performed by modulo division with the queue
size. That is,

if REAR + 1 == 5 (overflow!), REAR = (REAR+1) % 5 = 0 (start of queue)

Circular Queue Operations


The circular queue work as follows:

 two pointers FRONT and REAR

 FRONT track the first element of the queue


 REAR track the last elements of the queue
 initially, set value of FRONT and REAR to -1
1. Enqueue Operation

 check if the queue is full


 for the first element, set value of FRONT to 0
 circularly increase the REAR index by 1 (i.e. if the rear reaches the end,
next it would be at the start of the queue)
 add the new element in the position pointed to by REAR

Algorithm:

1. If ( FRONT = 0 && REAR = MAX – 1) ||(REAR = FRONT-1) then

Write “Overflow”
Goto step 4
[End of If]
2. If FRONT = -1 && REAR = -1 then

Set fRONT = REAR = 0

Else if REAR = MAX – 1 && FRONT != 0

Set REAR = 0

Else
Set REAR = (REAR + 1) % MAX

[End of If]
3. Set queue[ REAR ] = val
4. Exit
However, to check for full queue has following case:

 Case 1: FRONT == 0 && REAR == SIZE - 1

 Case 2: FRONT == REAR + 1

The second case happens when REAR starts from 0 due to circular increment
and when its value is just 1 less than FRONT , the queue is full.

2. Dequeue Operation

 check if the queue is empty


 return the value pointed by FRONT

 circularly increase the FRONT index by 1


 for the last element, reset the values of FRONT and REAR to -1
Algorithm:

1. If FRONT = -1

Write “Underflow”
Goto Step 4

[End of If]

2. Set val = queue[FRONT]

3. If FRONT = REAR

Set FRONT = REAR = -1

Else if FRONT = MAX – 1

Set FRONT = 0

Else

Set FRONT = (FRONT + 1) % MAX

[End of if]

[End of if]

4. Exit

Fig: Enqueue and Dequeue Operations


Circular Queue Implementations in C
The most common queue implementation is using arrays, but it can also be
implemented using lists.
// Circular Queue implementation in C
#include <stdio.h>
#define SIZE 5
int items[SIZE];
int front = -1, rear = -1;
// Check if the queue is full
int isFull() {
if ((front == rear + 1) || (front == 0 && rear == SIZE - 1)) return 1;
return 0;
}
// Check if the queue is empty
int isEmpty() {
if (front == -1) return 1;
return 0;
}

// Adding an element
void enQueue(int element) {
if (isFull())
printf("\n Queue is full!! \n");
else {
if (front == -1) front = 0;
rear = (rear + 1) % SIZE;
items[rear] = element;
printf("\n Inserted -> %d", element);
}
}
// Removing an element
int deQueue() {
int element;
if (isEmpty()) {
printf("\n Queue is empty !! \n");
return (-1);
} else {
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
// Q has only one element, so we reset the
// queue after dequeing it. ?
else {
front = (front + 1) % SIZE;
}
printf("\n Deleted element -> %d \n", element);
return (element);
}
}
// Display the queue
void display() {
int i;
if (isEmpty())
printf(" \n Empty Queue\n");
else {
printf("\n Front -> %d ", front);
printf("\n Items -> ");
for (i = front; i != rear; i = (i + 1) % SIZE) {
printf("%d ", items[i]);
}
printf("%d ", items[i]);
printf("\n Rear -> %d \n", rear);
}
}
int main() {
// Fails because front = -1
deQueue();

enQueue(1);
enQueue(2);
enQueue(3);
enQueue(4);
enQueue(5);
// Fails to enqueue because front == 0 && rear == SIZE - 1
enQueue(6);
display();
deQueue();
display();
enQueue(7);
display();

// Fails to enqueue because front == rear + 1


enQueue(8);
return 0;
}

Circular Queue Complexity Analysis


The complexity of the enqueue and dequeue operations of a circular queue
is O(1) for (array implementations).
Applications of Circular Queue
 CPU scheduling

 Memory management
 Traffic Management

Priority Queue
 A priority queue is a special type of queue in which each element is
associated with a priority value.
 And, elements are served on the basis of their priority. That is, higher
priority elements are served first.
 However, if elements with the same priority occur, they are served
according to their order in the queue.

Assigning Priority Value


Generally, the value of the element itself is considered for assigning the
priority.

For example, the element with the highest value is considered the highest
priority element. However, in other cases, we can assume the element with
the lowest value as the highest priority element.

We can also set priorities according to our needs.

Fig: Removing Highest Priority Element

Advantages of Priority Queue:

5. Simplicity
6. Reasonable support for priority
7. The most important tasks having higher priority are performed first
8. Important tasks do not have to wait for completion of less priority tasks
9. Suitable for applications with varying time and resource requirements

Applications of priority queue:

1. Priority queues can be used in OS for the purpose of job scheduling. Here,
the job with higher priority gets processed first.
2. Simulation systems in which priority corresponds to event times.
3. Graph algorithms such as Dijkstra’s shortest path algorithm, Prim’s minimum
spanning tree etc.
4. All queue applications where priority involved.

Difference between Priority Queue and Normal Queue

In a queue, the first-in-first-out rule is implemented whereas, in a priority queue,


the values are removed on the basis of priority. The element with the highest
priority is removed first.

Differentiate between Linear Queue and Circular Queue

Linear Queue Circular Queue

A linear DS that stores data as a sequence A linear DS in which the last item
of element similar to a real-world queue. connects back to the first item forming a
circle.

Possible to enter new items from rear end Possible to enter and remove elements
and remove the items from the front. from any position.

Requires more memory. Requires less memory.

Less efficient. More efficient.

You might also like