QueueMedium

Circular Queue

Circular Queue Data Structure

Circular Queue Data Structure

A Circular Queue is an extended version of a linear queue that resolves space wastage by conceptually joining the end of the array back to the beginning to form a loop.

Why Do We Need a Circular Queue?

In a standard linear queue, once rear reaches the end index (MAX - 1), you cannot insert more elements even if there is vacant space at the beginning due to preceding dequeues.

A circular queue overcomes this limitation using modulo arithmetic to wrap pointers back to index 0:

  • Pointer Increment: index = (index + 1) % MAX

Key Operations & Modulo Conditions

  1. Queue Full Check:

    isFull = ((rear + 1) % MAX == front)
    

    If the next cell after rear wraps around directly to front, the queue is full.

  2. Queue Empty Check:

    isEmpty = (front == -1)
    
  3. Circular Enqueue:

    • If empty: set front = 0, rear = 0.
    • Else: increment rear circularly: rear = (rear + 1) % MAX.
    • Store: arr[rear] = value.
  4. Circular Dequeue:

    • Access value: value = arr[front].
    • If only 1 element left (front == rear): reset pointers to -1.
    • Else: increment front circularly: front = (front + 1) % MAX.