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 the linked list implementation, the last node links back to the front node. In this post, you are going to implement circular queue using an array.

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 element respectively. When the queue is empty, they are -1. length is to keep track the numbers 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 increases frontIndex by 1. If frontIndex exceeds maxSize, you set frontIndex to index 0. This can be done by using modulo operation (“mod” or “%”). Please note: to dequeue element, 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 a circular queue. Starting from frontIndex, you use a for-loop to iterate through each slots 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