Queues in Data Structure
A Queue is a linear FIFO (First-In, First-Out) data structure where elements are added at the rear (enqueue) and removed from the front (dequeue). Common variants include circular, double-ended (deque), and priority queues, typically running in O(1) time.
Theory & Explanation
Queues: Operations, Circular Queue, Array & Linked Implementation, Deque & Priority Queue
1. Definition & FIFO Principle
A Queue is a linear data structure that follows the FIFO (First-In, First-Out) principle: the element inserted first is the first one to be removed. Unlike a stack (which uses one end, Top), a standard queue uses two ends:
- Rear (Back): The end where new elements are added (Enqueue / Add).
- Front (Head): The end from which elements are removed (Dequeue / Delete).
Real-Life Examples (For Exam Answers): People standing in a ticket or bank queue, print jobs waiting in a printer spooler, and processes waiting in a CPU ready queue.
2. Operations on a Queue: Create, Add, Delete, Full, and Empty
- Create / Initialize: Allocates memory or defines a structure and sets pointers/indices to indicate an empty queue (e.g.,
front = -1, rear = -1for a linear array queue, orfront = NULL, rear = NULLfor a linked queue). - Add (Enqueue): Inserts an element at the
rearafter checking whether the queue is full (Queue Overflow). In a linear array queue, when inserting the first element, bothfrontandrearmove from-1to0; subsequent additions incrementrear. - Delete (Dequeue): Removes and returns the element at the
frontafter checking whether the queue is empty (Queue Underflow). In a linear array queue, iffront == rearafter deletion, both reset to-1; otherwisefrontincrements by1. - Full (IsFull): Checks if no more elements can be added. In a linear array of size
MAX, it is full whenrear == MAX - 1. (Note: in a simple linear array, even if front elements were deleted,rear == MAX - 1blocks new additions—a drawback solved by a circular queue.) - Empty (IsEmpty): Checks if the queue has no elements (
front == -1in a linear array queue, orfront == NULLin a linked queue).
Step-by-Step Trace (Linear Queue of Capacity MAX = 3)
| Operation | front | rear | Queue Contents (Front → Rear) | Status / Output |
|---|---|---|---|---|
create() |
-1 |
-1 |
[ ] |
Empty (isEmpty = true) |
add(10) |
0 |
0 |
[ 10 ] |
Added 10 |
add(20) |
0 |
1 |
[ 10, 20 ] |
Added 20 |
add(30) |
0 |
2 |
[ 10, 20, 30 ] |
Added 30 (isFull = true) |
add(40) |
0 |
2 |
[ 10, 20, 30 ] |
Queue Overflow |
delete() |
1 |
2 |
[ 20, 30 ] |
Deleted 10 |
delete() |
2 |
2 |
[ 30 ] |
Deleted 20 |
delete() |
-1 |
-1 |
[ ] |
Deleted 30 (Empty) |
delete() |
-1 |
-1 |
[ ] |
Queue Underflow |
3. Circular Queue
A Circular Queue connects the last position of a fixed-size array back to the first position using modulo arithmetic (% MAX), forming a logical circle. This reuses freed slots at the front after deletions so space is not wasted.
- Advance Rear:
rear = (rear + 1) % MAX - Advance Front:
front = (front + 1) % MAX - Empty Condition:
front == -1 - Full Condition:
(rear + 1) % MAX == front
Example: For MAX = 4, if front = 1 and rear = 0 (with elements at indices 1, 2, 3, 0), then (0 + 1) % 4 == 1 == front, indicating the circular queue is full.
4. Array and Linked Implementation of Queues in C (and Python)
Just like stacks, queues can be implemented using a static/fixed array (contiguous memory, fixed capacity, no pointer overhead) or a singly linked list with front and rear pointers (dynamic size, grows at runtime, extra pointer per node). Both achieve O(1) time for enqueue and dequeue.
C Program: Circular Queue (Array Implementation)
#include <stdio.h>
#define MAX 4
int cq[MAX];
int front = -1, rear = -1;
int isFull() {
return ((rear + 1) % MAX) == front;
}
int isEmpty() {
return front == -1;
}
void enqueue(int val) {
if (isFull()) {
printf("Circular Queue Overflow! Cannot insert %d\n", val);
return;
}
if (isEmpty()) {
front = rear = 0;
} else {
rear = (rear + 1) % MAX;
}
cq[rear] = val;
printf("Enqueued %d\n", val);
}
int dequeue() {
if (isEmpty()) {
printf("Circular Queue Underflow! Queue is empty\n");
return -1;
}
int val = cq[front];
if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % MAX;
}
printf("Dequeued %d\n", val);
return val;
}
int main() {
enqueue(10);
enqueue(20);
enqueue(30);
enqueue(40);
enqueue(50); // Overflow
dequeue();
dequeue();
enqueue(50); // Reuses freed space
enqueue(60);
while (!isEmpty()) {
dequeue();
}
dequeue(); // Underflow
return 0;
}
Expected Output (C - Circular Queue):
Enqueued 10
Enqueued 20
Enqueued 30
Enqueued 40
Circular Queue Overflow! Cannot insert 50
Dequeued 10
Dequeued 20
Enqueued 50
Enqueued 60
Dequeued 30
Dequeued 40
Dequeued 50
Dequeued 60
Circular Queue Underflow! Queue is empty
C Program: Linked List Implementation of Queue
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node next;
};
struct Node front = NULL;
struct Node rear = NULL;
int isEmpty() {
return front == NULL;
}
void enqueue(int val) {
struct Node newNode = (struct Node )malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Queue Overflow! Heap memory full\n");
return;
}
newNode->data = val;
newNode->next = NULL;
if (rear == NULL) {
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
printf("Enqueued %d\n", val);
}
int dequeue() {
if (isEmpty()) {
printf("Queue Underflow! Queue is empty\n");
return -1;
}
struct Node temp = front;
int val = temp->data;
front = front->next;
if (front == NULL) {
rear = NULL;
}
free(temp);
printf("Dequeued %d\n", val);
return val;
}
int main() {
enqueue(100);
enqueue(200);
enqueue(300);
dequeue();
dequeue();
dequeue();
dequeue(); // Underflow
return 0;
}
Expected Output (C - Linked Queue):
Enqueued 100
Enqueued 200
Enqueued 300
Dequeued 100
Dequeued 200
Dequeued 300
Queue Underflow! Queue is empty
Python Program: Circular Queue & Linked Queue
class CircularQueue:
def __init__(self, capacity):
self.capacity = capacity
self.items = [None] * capacity
self.front = -1
self.rear = -1
def is_empty(self):
return self.front == -1
def is_full(self):
return ((self.rear + 1) % self.capacity) == self.front
def enqueue(self, val):
if self.is_full():
print(f"Circular Queue Overflow! Cannot insert {val}")
return
if self.is_empty():
self.front = self.rear = 0
else:
self.rear = (self.rear + 1) % self.capacity
self.items[self.rear] = val
print(f"Enqueued {val}")
def dequeue(self):
if self.is_empty():
print("Circular Queue Underflow! Queue is empty")
return None
val = self.items[self.front]
if self.front == self.rear:
self.front = self.rear = -1
else:
self.front = (self.front + 1) % self.capacity
print(f"Dequeued {val}")
return val
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedQueue:
def __init__(self):
self.front = None
self.rear = None
def is_empty(self):
return self.front is None
def enqueue(self, val):
node = Node(val)
if self.rear is None:
self.front = self.rear = node
else:
self.rear.next = node
self.rear = node
print(f"Enqueued {val}")
def dequeue(self):
if self.is_empty():
print("Queue Underflow! Queue is empty")
return None
val = self.front.data
self.front = self.front.next
if self.front is None:
self.rear = None
print(f"Dequeued {val}")
return val
cq = CircularQueue(4)
cq.enqueue(10)
cq.enqueue(20)
cq.enqueue(30)
cq.enqueue(40)
cq.enqueue(50)
cq.dequeue()
cq.dequeue()
cq.enqueue(50)
cq.enqueue(60)
while not cq.is_empty():
cq.dequeue()
cq.dequeue()
lq = LinkedQueue()
lq.enqueue(100)
lq.enqueue(200)
lq.dequeue()
lq.dequeue()
lq.dequeue()
Expected Output (Python):
Enqueued 10
Enqueued 20
Enqueued 30
Enqueued 40
Circular Queue Overflow! Cannot insert 50
Dequeued 10
Dequeued 20
Enqueued 50
Enqueued 60
Dequeued 30
Dequeued 40
Dequeued 50
Dequeued 60
Circular Queue Underflow! Queue is empty
Enqueued 100
Enqueued 200
Dequeued 100
Dequeued 200
Queue Underflow! Queue is empty
5. Deque (Double-Ended Queue)
A Deque (Double-Ended Queue) is a linear data structure in which insertion and deletion can be performed at both ends (front and rear). It can behave both as a FIFO queue and as a LIFO stack.
- Basic Operations:
insertFront(),insertRear(),deleteFront(),deleteRear(), plusgetFront(),getRear(),isEmpty(), andisFull(). - Input-Restricted Deque: Insertion is allowed at only one end (e.g., rear), while deletion is allowed at both ends (front and rear).
- Output-Restricted Deque: Deletion is allowed at only one end (e.g., front), while insertion is allowed at both ends (front and rear).
6. Priority Queue
A Priority Queue is an abstract data type similar to a queue, except each element has an associated priority. Elements with higher priority are dequeued before elements with lower priority; elements with the same priority are served in FIFO order.
- Ascending vs. Descending Priority: Depending on convention, a smaller number (e.g., priority
1before5) or a larger number may represent higher priority—state your convention clearly in exams. - Common Implementations: Unsorted/sorted array or linked list, or a Binary Heap (Min-Heap / Max-Heap), which gives
O(log n)insertion and extraction. - Example & Applications: Emergency room triage (critical patients first), OS process/interrupt scheduling, and graph algorithms like Dijkstra's shortest path.
| Queue Type | Insertion End(s) | Deletion End(s) | Ordering Rule |
|---|---|---|---|
| Simple / Linear Queue | Rear only | Front only | Strict FIFO |
| Circular Queue | Rear (wraps via % MAX) |
Front (wraps via % MAX) |
FIFO with circular space reuse |
| Deque | Front and/or Rear | Front and/or Rear | Flexible (supports FIFO & LIFO) |
| Priority Queue | By priority | Highest priority element first | Priority order (FIFO for ties) |
