Implement circular queue using an array

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 the array implementation, the index of the rear element wraps around to the beginning of the array. In this post, you are going to implement a circular queue using an array in Java, JavaScript and Python.

circular queue diagram

Table of Content


Enqueue

First, you declare an array. maxSize is the max length of the array. frontIndex and rearIndex are the indices of the front and rear elements respectively. When the queue is empty, they are -1. length is to keep track of the number of elements in the queue.

Enqueue is to add an element at the back and increase rearIndex by 1. If rearIndex exceeds maxSize, you use modulo operation (“mod” or “%”) to get a new rearIndex within maxSize.

Java

Javascript

Python


Dequeue in circular queue implementation

The dequeue operation is to remove the front element from a 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 frontIndex by 1. If frontIndex exceeds maxSize, you use the modulo operation to set frontIndex within maxSize. Please note: to dequeue elements, you only update frontIndex. The element in the original frontIndex stays in the spot until it is replaced by a new value.

Java

Javascript

Python


Peek

Peek is to return the value at firstIndex. You 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, you use a for loop to iterate through each slot till to rearIndex. In each iteration, the index i is increased by 1, then mod by maxSize.

Java

Javascript

Python


Free download

Download CircularQueueArray.java
Download CircularQueueArray.js
Download CircularQueueArray.py

Comments are closed