A circular queue is a queue in which all elements are connected to form a circular. A circular queue can be implemented with an array or a linked list. In array implementation, the front and rear wrap-around (modulo operation) to the beginning of the array. In this post, circular queue implementation uses using an array.

circular queue diagram

Table of Content


Map of queue implementations

Part 1 – Queue implementation using a linked list

you are here

Part 2 – Circular queue implementation using an array
Part 3 – Circular queue (Circular linked list)
Part 4 – Deque (Doubly linked list)


Enqueue in circular queue implementation

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

To enqueue is to add an element at the rear. rearIndex is increased by 1. If the rearIndex exceeds the maxSize, you use the modulo operation (or “mod”, “%”) to get the new rearIndex with the maxSize range.

Java

Javascript

Python

Doodle

circular queue enqueue


Dequeue in circular queue implementation

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

To dequeue, you increase the frontIndex by 1. If frontIndex exceeds maxSize, you have to put the element back to index 0. You use the modulo operation (“mod”, “%”) to get the new frontIndex. Please note to dequeue elements, you only update frontIndex. The original value stays in the spot until it is replaced with the new value.

Java

Javascript

Python

Doodle

circular queue dequeue


Peek

Peek is to return the value at firstIndex. Please also 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 frontIndex, a for loop or while loop can be used to iterate through each slot till to rearIndex. The index i is increased by 1, then mod maxSize.

Java

Javascript

Python


Free download

Download circular queue implementation in Java, JavaScript and Python
Data structures and Java collections

What is the wrap-around technique used in a circular queue?

The wrap-around is to use modulo operation to make sure frontIndex and rearIndex with the range of maxSize of the array. For example, to enqueue, the formula is rearIndex = (rearIndex + 1) % maxSize. To dequeue, it is frontIndex = (frontIndex + 1) % maxSize.