Course contentsShow
← Computer Science
Lesson 388 of 2,8729. Stacks and QueuesFree lesson

Circular Queue Operations

Enqueue and dequeue operations in circular queues, handling the wraparound logic correctly.

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:

  1. Check if the queue is full (to avoid overwriting data)
  2. Insert the new element at the rear position
  3. Move rear forward: 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:

  1. Check if the queue is empty (nothing to remove)
  2. Retrieve the element at the front position
  3. Move front forward: 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.