Circular Queue
1if count == capacity: overflow (the queue is full)2rear ← (rear + 1) mod capacity // wraps to 0 after the end3a[rear] ← v4count ← count + 1
What is a Circular Queue?
A circular queue (or ring buffer) is still a FIFO queue on an array, but the array's ends are joined: after the last slot comes slot 0 again. Both front and rear move forward with (index + 1) mod capacity, so slots freed by dequeue are reused by later enqueues.
The ring on the left and the flat array on the right show the same eight slots. Watch rear jump from slot 7 back to slot 0: on the ring it's just the next slot, in the array it wraps to the start.
next = (index + 1) mod capacity: the end of the array wraps round to the start.
How the Operations Work
Enqueue
If count < capacity, advance rear one step round the ring, store the value and add one to count.
Dequeue
If count > 0, read a[front], advance front one step round the ring and take one off count.
Why keep a count?
In an empty queue and in a full queue, rear sits just before front. The count tells the two apart. (Another common trick is to always leave one slot empty.)
Compared to the simple queue
The simple array queue can only use each slot once. The circular queue keeps reusing them, so it can run forever with a fixed amount of memory.
Implementation
Properties & Complexity
Time Complexity
- • Enqueue: O(1)
- • Dequeue: O(1)
- • Peek: O(1)
- • Is empty / full: O(1)
Space & Properties
- • Space: exactly the capacity
- • Order: FIFO
- • Slots: all reused, none wasted
- • Allocation: none after creation
Where Ring Buffers Are Used
- • Audio and video streaming: a steady buffer of samples
- • Keyboard and serial input: drivers store key presses
- • Network cards: packets waiting to be processed
- • Logs: keep only the latest N entries
- • Round-robin scheduling: take turns forever
Limitations
- • Fixed capacity: it overflows when every slot is full
- • Empty vs full: needs a count or a spare slot to tell apart
- • No random access: only the front can be read