Circular Queue Operations
You'll learn how to enqueue and dequeue elements in a circular queue while correctly handling the wraparound logic.
The Core Challenge
In a circular queue, when you reach the end of the underlying array, you need to "wrap around" to the beginning—but only if there's space available. This means both enqueue (adding) and dequeue (removing) operations must account for this circular nature.
Enqueue Operation
When adding an element:
- Check if the queue is full (to avoid overwriting data)
- Insert the new element at the
rearposition - Move
rearforward:rear = (rear + 1) % capacity
The modulo operator (%) is key—it wraps rear back to 0 when it exceeds the array's end.
Example: In a queue with capacity 5, if rear is at index 4, after enqueue: rear = (4 + 1) % 5 = 0 (wraps to start).
Dequeue Operation
When removing an element:
- Check if the queue is empty (nothing to remove)
- Retrieve the element at the
frontposition - Move
frontforward:front = (front + 1) % capacity
Again, modulo ensures front wraps around circularly.
The Wraparound Logic
Think of it like a clock face: after 12 comes 1, not 13. Similarly, after the last array index comes index 0. The modulo operation mathematically enforces this circular behavior, preventing index-out-of-bounds errors while maximizing array reuse.
Both operations must also update the queue's size counter (increment for enqueue, decrement for dequeue) to distinguish between "empty" and "full" states when front and rear overlap.
Key Takeaway: Circular queue operations use modulo arithmetic (index + 1) % capacity to wrap indices around the array boundaries, enabling efficient reuse of space without shifting elements.