I recently had a requirement of using a queue data structure whose length was finite due to memory constraints, and hence I preferred to adopt the circular queue data structure. When I searched for a circular queue over the internet, I could not find much, so I decided to write this article.
A circular queue follows the basic rules of a queue data structure. It has the first in first out mechanism, but its size is restricted. We just need to keep track of two terms to understand, implement, and use a circular queue; they are:
- Front position (from where you can dequeue)
- Rear position (the last element's position in the queue)
I have implemented this in C# using the
ArrayList data type.
The two methods that we expose are
Dequeue (the traditional queue methods). I have also added a
ResetQueue method to reset the queue to its initial state. The main requirement for this type of a data structure is to implement a restricted number of place holders which can hold an instance of the object that is inserted in to the queue.
In the constructor, our circular queue class will accept an integer parameter to set its
MaxQueueSize property. The whole queue implementation is based on the maximum queue size. In any typical application scenario, this maximum size needs to be selected based on the amount of memory an object instance will take and how much memory can be allotted for our queue. Initially,
FrontPosition is set to zero and
RearPosition to -1.
If the queue has any vacant position, the
Enqueue method will add an element (object) to the circular queue at
RearPosition+1. If there is no vacant position, the method will return
public bool Enqueue(object obj)
if((nRearPosition == (nMaxSize-1) && nFrontPosition==0) ||
if(nRearPosition == (nMaxSize -1) && nFrontPosition > 0)
nRearPosition = -1;
alstQueueContent[nRearPosition] = obj;
if((nRearPosition-1) == nFrontPosition &&
nFrontPosition = nFrontPosition+1;
If the queue has any element at the position pointed by
Dequeue method will remove the element (object) from the circular queue and increment
MaxSize -1, then after the dequeue operation,
FrontPosition must be set to 0 instead of incrementing.
public object Dequeue()
object Output = "Empty" ;
if(alstQueueContent[nFrontPosition] != null)
Output = alstQueueContent[nFrontPosition];
nFrontPosition += 1;
else if(alstQueueContent !=null && (nFrontPosition+1)== nMaxSize)
nFrontPosition = 0;
The complete implementation is available ias a downloadable attachment.