Data Structures (Chapter-05 Queue)
Data Structures (Chapter-05 Queue)
STRUCTURES
WITH COMPETITIVE
CODING
Presented By: Mr. Satyananda Swain
Assistant Professor, Computer Science Engineering,
❑ A Queue is like a line waiting to purchase tickets, where the first person in line is the first person served. (i.e.
First Come First Serve). Position of the entry in a queue ready to be served, that is, the first entry that will be
removed from the queue, is called the front of the queue(sometimes, head of the queue). Similarly, the position
of the last entry in the queue, that is, the one most recently added, is called the rear (or the tail) of the queue.
❑ Simple Queue: Simple Queue simply follows a FIFO Structure. We can only insert the element at the back and remove the element from the front of the queue.
❑ Circular Queue: This is a special type of queue where the last position is connected back to the first position. Here also the operations are performed in FIFO
order.
❑ Double-Ended Queue (Dequeue): In a double-ended queue the insertion and deletion operations, both can be performed from both ends. They are of two
types:
▪ Input Restricted Queue: This is a simple queue. In this type of queue, the input can be taken from only one end but deletion can be done from any end.
▪ Output Restricted Queue: This is also a simple queue. In this type of queue, the input can be taken from both ends but deletion can be done from only
one end.
❑ Priority Queue: A priority queue is a special queue where the elements are accessed based on the priority assigned to them. They are of two types:
▪ Ascending Priority Queue: In Ascending Priority Queue, the elements are arranged in increasing order of their priority values. Element with smallest
priority value is popped first.
▪ Descending Priority Queue: In Descending Priority Queue, the elements are arranged in decreasing order of their priority values. Element with largest
priority is popper first.
▪ Enqueue: Adds (or stores) an element to the rear end of the queue.
▪ Traverse: Display all the data elements available in the queue without
removing them.
▪ Using Array
❑ To implement a queue using a simple array, create an array of size n and take two variables front and
rear, both of which will be initialized to 0, which means the queue is currently empty. Element:
▪ rear is the index up to which the elements are stored in the array and
❑ In a linked list-based implementation, the enqueue operation is implemented by creating a new node
with the new element and setting the next pointer of the current rear node to the new node. The dequeue
operation is implemented by setting the start pointer to point to the next pointer of the front node and
returning the value of the current front node.
▪ Here, the QUEUE is a Linear Array of elements following the FIFO Step 2.1) Print “OVERFLOW” and Return.
Principle. [End of if of Step-2]
▪ FRONT is a variable storing the index value of the Front element Step 3: If (FRONT = 0 and REAR = 0), then:
of the QUEUE.
Step 3.1) Set FRONT : = 1 and REAR : = 1.
▪ REAR is a variable storing the index value of the Rear or Last
Step 4: Else, then:
element of the QUEUE.
Step 4.1) Set REAR : = REAR + 1.
▪ N is the Maximum number of elements that can be stored in the
QUEUE. [End of if of Step-3]
This algorithm is used to insert ITEM at the REAR end of QUEUE. Step 6: Stop.
Step 2: Let I.
❑ Algorithm: TRAVERSE_QUEUE (QUEUE, FRONT, REAR)
Step 3: If (FRONT = 0), then:
▪ Here, the QUEUE is a Linear Array of elements following
Step 3.1) Print “Empty Queue” and Return.
the FIFO Principle.
[End of if of Step-3]
▪ FRONT is a variable storing the index value of the Front
Step 4: Repeat For I : = FRONT to REAR incremented
element of the QUEUE.
by 1, then:
▪ REAR is a variable storing the index value of the Rear
Step 4.1) Apply PROCESS/ Print QUEUE[I].
or Last element of the QUEUE.
[End of Loop of Step-4]
This algorithm is used to display all the elements of QUEUE in
Step 5: Stop.
FIFO order.
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
SCHOOL OF ENGINEERING AND TECHNOLOGY, CENTURION UNIVERSITY, BHUBANESWAR, ODISHA
isEmpty Operation 9
#include<stdio.h> return 0;
#include<stdlib.h> }
typedef struct {
{ if(q->r==MAX-1)
}queue; else
{ }
if(q->f==-1 )
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
SCHOOL OF ENGINEERING AND TECHNOLOGY, CENTURION UNIVERSITY, BHUBANESWAR, ODISHA
Linear Queue Operations: Complete C Code 12
void display(queue *q) {
{ if(isfull(q))
int i; printf("\nOVERFLOW\n");
printf("\nQueue Empty\n"); {
else q->f=0;q->r=0;q->a[q->r]=x;
{ }
for(i=q->f;i<=q->r;i++) {
printf("%d\t",q->a[i]); q->r++;
printf("\n\n"); q->a[q->r]=x;
} }
} display(q);
{ q->f++;
if(isempty(q)) display(q);
{ }
printf("\nUNDERFLOW\n"); return;
x=q->a[q->f];
if(q->f==q->r)
q->f=q->r=-1;
{ scanf("%d",&item);
queue q; qinsert(&q,item);break;
do case 4: exit(0);
printf("\nPRESS:\n1->INSERT\n2->DELETE\n3->DISPLAY\n }
scanf("%d",&option); }
switch(option)
❑ If the last position of the queue is occupied, it is not possible to enqueue any more
elements even though some positions are vacant towards the front positions of the
queue.
❑ On deleting an element from the existing queue, the front pointer is shifted to the next
position. •This results in the virtual deletion of an element. By doing so, memory space
occupied by deleted elements is wasted, hence inefficient memory utilization.
❑ To overcome the disadvantage of the linear queue, the circular queue is used.
❑ We can solve this problem by joining the front and rear ends of a queue to make the
queue a circular queue. In a circular queue, the last node is connected to the first node
to make a circle.
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
SCHOOL OF ENGINEERING AND TECHNOLOGY, CENTURION UNIVERSITY, BHUBANESWAR, ODISHA
Circular Queue 16
❑ A Circular Queue is an extended version of a linear queue where the last element of the queue is
connected to the first element of the queue forming a circle.
❑ The operations are performed based on FIFO (First In First Out) principle. It is also called ‘Ring
Buffer’.
▪ Enqueue: Adds (or stores) an element to the rear end of the queue.
▪ Traverse: Display all the data elements available in the queue without removing them.
▪ Using Array
❑ To implement a circular queue using a simple array, create an array of size n and take two variables
front and rear, both of which will be initialized to 0, which means the queue is currently empty. Element:
▪ rear is the index up to which the elements are stored in the array and
❑ In a linked list-based implementation, the enqueue operation is implemented by creating a new node
with the new element and setting the next pointer of the current rear node to the new node. The dequeue
operation is implemented by setting the start pointer to point to the next pointer of the front node and
returning the value of the current front node.
❑ Algorithm : CQINSERT(CQUEUE, FRONT, REAR, N, ITEM) Step 2: If (FRONT = 1 and REAR = N or FRONT = REAR + 1), then:
▪ FRONT is a variable storing the index value of the Front Step 3.1) Set FRONT : = 1 and REAR : = 1.
element of the CQUEUE. Step 4: Else if (REAR = N), then:
▪ REAR is a variable storing the index value of the Rear or Last Step 4.1) Set REAR : = 1.
element of the CQUEUE.
Step 5: Else, then:
▪ N is the Maximum number of elements stored in the QUEUE. Step 5.1) Set REAR : = REAR + 1. [End of if of Step-3]
▪ ITEM is the element to be inserted. Step 5: Set CQUEUE[REAR] : = ITEM.
This algorithm is used to insert ITEM at the REAR end of CQUEUE. Step 6: Stop.
❑ Dequeue operation removes an item from the front end of Step 1: Start.
the circular queue. If the circular queue is empty, it is Step 2: Let ITEM.
considered an Underflow condition. Step 3: If (FRONT = 0), then:
❑ Algorithm : CQDELETE(CQUEUE, FRONT, REAR) Step 3.1) Print “UNDERFLOW” and Return.[End of if of Step-3]
▪ Here, the CQUEUE is a Linear Array of elements Step 4: If(FRONT < = REAR), then:
Front element of the CQUEUE. Step 5.1)Repeat For I : = FRONT to N incremented by 1, then:
[End of if of step-4]
This algorithm displays all the elements of CQUEUE in FIFO
Step 6: Stop.
order.
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
SCHOOL OF ENGINEERING AND TECHNOLOGY, CENTURION UNIVERSITY, BHUBANESWAR, ODISHA
isEmpty Operation 23
▪ Algorithmically, If (FRONT = 1 and REAR = N or FRONT = REAR + 1), then the CQueue is full
so return true.
▪ Programmatically, If (FRONT == 0 and REAR == N-1 or FRONT = REAR + 1), then the CQueue
#include<stdio.h> return 0;
#include<stdlib.h> }
typedef struct {
}cqueue; else
{ }
{ else
int i; {
if(isempty(q)) for(i=q->f;i<=MAX-1;i++)
{ printf("%d\t",q->a[i]);
} printf("%d\t",q->a[i]);
else }
{ printf("\n\n");
if(q->f<=q->r) }
for(i=q->f;i<=q->r;i++)
{ q->r=0;
if(isfull(q)) q->a[q->r]=x;
{ }
printf("\nOVERFLOW\n"); else
} {
{ q->a[q->r]=x;
q->f=0;q->r=0;q->a[q->r]=x; }
} display(q);
else if(q->r==MAX-1) }
{ else if (q->f==MAX-1)
int x; q->f=0;
if(isempty(q)) else
{ q->f++;
return; display(q);
} }
x=q->a[q->f];
if(q->f==q->r)
do case 3: display(&cq);break;
{ case 4: exit(0);
❑ Double-ended Queue is also a Queue data structure in which the insertion and deletion operations are
performed at both ends (front and rear). That means, we can insert at both front and rear positions and
❑ In this type of Queue, the input can be taken from one side only(rear) and deletion of elements can be
done from both sides(front and rear). This kind of Queue does not follow FIFO(first in, first out). This
queue is used in cases where the data consumption needs to be in FIFO order but if there is a need to
❑ In this type of Queue, the input can be taken from both sides(rear and front) and the deletion of the
element can be done from only one side(front). This queue is used in the case where the inputs have
some priority order to be executed and the input can be placed even in the first place so that it is
executed first.
priority values are typically retrieved before elements with lower priority values. There are two types of Priority
❑ Ascending Priority Queue: Element can be inserted arbitrarily, but only the smallest element can be removed. For
example, suppose an array has elements 4, 2, and 8 in the same order. So, while inserting the elements, the
insertion will be in the same sequence but the order will be 2, 4, 8 while deleting.
❑ Descending priority Queue: Element can be inserted arbitrarily but only the largest element can be removed first
from the given Queue. For example, suppose an array has elements 4, 2, and 8 in the same order. So, while inserting
the elements, the insertion will be in the same sequence but while deleting, the order will be 8, 4, 2.
❑ There are several ways to implement a priority queue, including using an array, linked list, heap, or BST.
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
SCHOOL OF ENGINEERING AND TECHNOLOGY, CENTURION UNIVERSITY, BHUBANESWAR, ODISHA
Advantages of Queue 35
Queues provide several key advantages that make them a ubiquitous data structure in programming. The main benefits
are:
❑ Ordering: Queues maintain the original order of insertion for elements. The first element inserted is also the first
one out. This First-In-First-Out (FIFO) ordering ensures sequenced access and processing..
❑ Synchronization: Queues can synchronize and transfer data safely between multiple threads or processes.
❑ Decoupling: Queues allow the decoupling of different components or services in a system. The queue acts as an
❑ Load Leveling: Queues smooth uneven loads and prevent resource overloading. Temporary spikes in traffic or load
operations are enqueued. The queue allows resuming when the result is available.
❑ Fault Tolerance: Queues implement reliable delivery even across system failures. Elements persist in the queue
❑ Traffic Burst Buffering: Queues can buffer short bursts of traffic. Temporary incoming spikes beyond service
❑ Resource Pooling: Queues allow pooling of servicing resources like threads and database connections. Resources
❑ Rate Limiting: Queues can be used to rate limit tasks and prevent resource overuse. Elements are added to a queue
Although queues provide many benefits, they also come with some disadvantages:
❑ No Random Access: Queues only allow sequential access to elements. There is no way to access an arbitrary
element in the queue directly. Elements must be dequeued in order from the front. This makes queues unsuitable
❑ Additional Memory Overhead: Queues require extra memory to handle the buffering and ordering of elements. All
elements must be stored until processed. For a system processing data "in place", a queue solution incurs
overhead.
❑ Increased Processing Latency: Queues inherently introduce delays as elements wait to be processed in order.
Elements queued earlier must be completed before later ones begin processing. This increases processing latency.
removed until they reach the font. Priority changes cannot be accommodated.
❑ Additional Programming Complexity: Queues require managing the order, storage and access of elements.
Additional code must handle queue insertion, removal and overflow. This increases software complexity.
❑ Not Cache Friendly: Queues lack locality of reference and access elements sequentially. This prevents efficient use
of caches during access. Caches work best with localized random access.
❑ Restricted Access: Queues only allow access to the front and rear elements. The only operations available are
enqueue and dequeue. This restricts the ability to organize and access data.
❑ Blocking Operations: Operations like dequeue can block and stall if the queue is empty. This can lead to poor
performance and starvation for other waiting processes. Care must be taken to prevent blocking where possible.
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
SCHOOL OF ENGINEERING AND TECHNOLOGY, CENTURION UNIVERSITY, BHUBANESWAR, ODISHA
Applications of Queue 39
Queues have various real-world applications since they allow efficient modelling of real queues and Ordering
❑ Operating Systems Scheduling: One of the most common uses of queues is for scheduling tasks in
operating systems. The OS maintains queues of processes waiting for important resources like CPU time,
memory, I/O devices, etc. Schedulers follow queue disciplines like FCFS, Priority Queueing, and round-
❑ Message Queuing: Message queues are used frequently in distributed applications. Various components
of an application interact by passing asynchronous messages. Queues store these messages reliably until
they are consumed. Message queues enable smooth data exchange between distributed systems.
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
SCHOOL OF ENGINEERING AND TECHNOLOGY, CENTURION UNIVERSITY, BHUBANESWAR, ODISHA
Applications of Queue 40
❑ Breadth-First Search: Queues are leveraged in graph and tree algorithms like breadth-first search to
traverse nodes layer by layer. Initially, the root node is enqueued. All its neighbours are then dequeued
❑ Printer Spooler: Operating systems and printer drivers use print queues to handle print requests. All
documents are spooled in a queue instead of being printed directly. The printer handles jobs sequentially
in a FIFO manner. Queues allow smooth handling of frequent print requests and prevent bottlenecks.
❑ Web Server Request Queuing: Web servers and frameworks leverage request queues to handle multiple
client requests concurrently. As requests come in, they are added to a queue and processed in order. The
❑ CPU Scheduling: OS kernels use queues for CPU scheduling. The processes waiting for CPU time are kept
❑ Traffic Modeling: Traffic systems maintain queues of vehicles waiting at signals, toll booths, etc. These
queues are modeled using queuing theory to analyze traffic patterns and optimize road networks.
❑ Order Processing: E-commerce systems leverage queues to smooth order processing and ensure
sequencing.
❑ Load Balancing: Queues can be used for load balancing in distributed systems. A central job queue is
created, and multiple worker processes are used to listen for jobs. Load balancing is a key application of