Queue operations revolve around two pointers: Front (for deletion) and Rear (for insertion). Enqueue adds an element at the Rear. Dequeue removes an element from the Front. Two critical error states exist: Overflow (enqueue when full) and Underflow (dequeue when empty).
Overflow: A roller coaster line hits maximum capacity. A bouncer says 'No more people allowed!' You try to enqueue but can't. Underflow: The ride operator looks at an empty line and asks 'Who am I letting on the ride? A ghost?' You try to dequeue but there's no one.
Watch how Front chases Rear!
Happens when you try to ENQUEUE but the line is full.
Bouncer says: "No more people allowed!"
Happens when you try to DEQUEUE but no one is in line.
Operator says: "Who am I letting on the ride? A ghost?"
1void enqueue(int value) {2if (rear == MAX - 1) {3printf("Queue Overflow!");4return; // No space left5}6rear++; // Move Rear forward7queue[rear] = value; // Place the person8}910int dequeue() {11if (front > rear) {12printf("Queue Underflow!");13return -1; // No one in line14}15int val = queue[front]; // Grab the front person16front++; // Move Front forward17return val;18}
The Mechanics of Enqueue and Dequeue
Enqueuing (Adding to the line):
1. First, check if the queue is full. (Is there room?)
2. If there is room, move the Rear pointer forward by one step.
3. Place the new item exactly where Rear is pointing.
Dequeuing (Removing from the line):
1. First, check if the queue is empty. (Is anyone in line?)
2. If it is not empty, grab the item at Front.
3. Move the Front pointer forward by one step.
Notice: Both pointers move in the SAME direction (forward). Rear chases ahead, Front follows behind. The space between them is your active queue.
The Two Nightmare Scenarios
1. Queue Overflow 🚫
Imagine a sold-out concert venue. The line stretches out the door, and the manager puts up a sign: "FULL — No More Entry." In code, when Rear reaches the maximum array size and you try to enqueue, you get a Queue Overflow error. The queue simply cannot hold any more items.
2. Queue Underflow 👻
Imagine a ride operator at an empty amusement park. There is literally no one in the line, but the operator tries to send the next person on the ride. There is no one to send! In code, when Front has no valid elements and you try to dequeue, you get a Queue Underflow error.
Peek — The Safe Check
Peek lets you look at the Front element without removing it. It's like the ride operator checking who is next in line without actually letting them on the ride yet. Time complexity: O(1).
Understanding how Front and Rear pointers move is essential to implement a queue correctly. Just like stacks have Overflow and Underflow, queues have the same — and there is an additional trap called 'False Overflow' unique to array-based queues that trips up many students.
"What causes a Queue Underflow error?"
A Queue Underflow occurs when you try to dequeue (remove) from an empty queue. There are no elements to remove.