Concept / Given Data
A Queue is a linear data structure that follows the FIFO (First In, First Out) principle. Insertion happens at the rear end and deletion at the front end. The two fundamental operations are:
- enqueue(x): insert element x at the rear.
- dequeue(): remove and return the element at the front.
Step-by-Step: Linear Queue Array Implementation in C
- Declare
int q[MAX], front = 0, rear = -1;
- enqueue(x): check
if (rear == MAX-1) → overflow; else q[++rear] = x;
- dequeue(): check
if (front > rear) → underflow; else return q[front++];
void enqueue(int x) {
if (rear == MAX-1) { printf("Queue full\n"); return; }
q[++rear] = x;
}
int dequeue() {
if (front > rear) { printf("Queue empty\n"); return -1; }
return q[front++];
}
Problem with Linear Queue
After several enqueue–dequeue cycles, front advances but the slots before front become permanently wasted. Even if free space exists at the front, the queue reports overflow because rear == MAX-1. This is the wasted-space problem.
Example: With MAX = 5, after enqueue(A), enqueue(B), enqueue(C), dequeue(), dequeue(), we have front = 2, rear = 2. Only slot 2 is occupied, yet rear cannot advance past index 4, so at most 2 more elements can be enqueued instead of 5.
Circular Queue — The Solution
In a circular queue, the array is treated as a ring. The rear wraps around using modulo arithmetic:
rear=(rear+1)modMAX
front=(front+1)modMAX
- Empty condition:
front == rear (with an initial front = 0, rear = -1 convention, or use a count variable).
- Full condition:
(rear + 1) % MAX == front.
This eliminates wasted space and allows the queue to reuse front slots.
Real-World Connect: A print spooler uses a queue — jobs are enqueued in arrival order and dequeued for printing in the same order. CPU task scheduling (Round-Robin) also uses a queue of ready processes.
Result: Linear queue wastes O(n) space after repeated operations; circular queue reuses all n slots efficiently with O(1) enqueue and dequeue.
Tip from Examiner: The question explicitly asks for the *problem* and the *idea* of circular queue — do not just write code. State the wasted-space issue in one sentence, then give the modulo formula. Examiners award 2 marks for the circular queue explanation alone. Common mistake: writing `rear == MAX` instead of `rear == MAX-1` for the full condition in a linear queue.