Topic 3
Circular Queue (Array)
Efficient Array Storage
The Problem with Simple Array Queue: When we dequeue elements, the spaces at the front of the array become empty, but the rear pointer keeps moving forward until it hits the end. We get a "Queue is Full" error even if there is space at the front!
The Solution: Circular Queue uses the modulo operator (% size) to wrap the rear (and front) pointers back to the beginning of the array, reusing empty spaces.
Circular Array (Wrapped)
๐ง
Modulo is the magic:
(rear + 1) % size wraps 4 back to 0 when size is 5.โ ๏ธ
isFull Condition:
(rear + 1) % size == front means the rear is right behind the front.๐
First Enqueue: If
front == -1, it must be set to 0 when the first item is added!๐
Dequeue: If
front == rear (only 1 element left), reset both to -1. Else, front = (front + 1) % size;circular-queue