In a circular queue, the last element points back to the first, forming a circular link.
The main advantage over a simple queue is better memory utilization: if the last position is full and the first position is empty, a new element can still be inserted at the first position — not possible in a simple queue, where a run of insertions and deletions leaves unusable empty space at the front.
Operations
- Two pointers,
FRONTandREAR, are used. FRONTtracks the first element.REARtracks the last element.- Initially, both are set to
-1.
Enqueue
- Check if the queue is full.
- For the first element, set
FRONTto0. - Circularly increase
REARby 1 (ifREARreaches the end, it wraps to the start). - Add the new element at the position pointed to by
REAR.
Dequeue
- Check if the queue is empty.
- Return the value pointed to by
FRONT. - Circularly increase
FRONTby 1. - For the last element, reset
FRONTandREARto-1.
Checking Full
The full check has an extra case beyond the simple queue:
- Case 1:
FRONT == 0 && REAR == SIZE - 1 - Case 2:
FRONT == REAR + 1
Case 2 happens when REAR wraps around to 0 and its value ends up just one less than FRONT.
Complexity
Enqueue and dequeue are both O(1) for the array implementation.