Circular queue is a queue in which all elements are connected to form a circular. Circular queue can be implemented with array and linked list. In array implementation, the front and rear wrap around (modulo operation) to the beginning of the array. In linked list implementation, the last node links back to the front node.

In this post, array is used to implement circular queue, so that the discarded slot can be reused. For linked list implementation, please refer circular linked list.

Table of Content


Enqueue

First we declare an array. In Java, if you use array (not ArrayList), you have to specify the maxSize. If the array reaches the maxSize, you cannot add more element. The frontIndex and rearIndex is the index of the front element and rear element. When the queue is empty, they are -1. The length is to keep track of the numbers of elements in the queue.

To enqueue is to add element at the rear. The rearIndex is increased by 1. If the rearIndex exceeds the maxSize, we have to put the element back to index 0 (if the slot is empty due to dequeue). We use modulo operation (or “mod”, “%”) to get the new rearIndex.

Java

Javascript

Python

Doodle

circular queue enqueue


Dequeue

The dequeue operation is to remove the front node from the queue. First we check whether the queue is empty. If it is empty, the method should return. We also check whether there is only one element in the queue. If it is, we should reset the frontIndex and rearIndex to -1 after removing the last element.

To dequeue, we increases the frontIndex by 1. Like enqueue, if the frontIndex exceeds the maxSize, we have to put the element back to index 0. We use modulo operation (or “mod”, “%”) to get the new frontIndex. Please note to dequeue element, we only update the frontIndex. The original value stays in the spot until it is replaced with new value.

Java

Javascript

Python

Doodle

circular queue dequeue


Peek

Peek is to return the value at the firstIndex. The same as dequeue, we should check whether the queue is empty. If it is not empty, return the value.

Java

Javascript

Python


Print

Print is to print all elements in the circular queue. Starting from the frontIndex, a for loop or while loop is used to iterate through each slots till to the rearIndex. Like enqueue and dequeue, the index i is increased by 1, then mod the maxSize.

Java

Javascript

Python

Download Java, JavaScript and Python code>
Circular queue animated visual
Data structures and Java collections