Circular Queue
Prepared by
Dr Senthil Kumar A M
Circular Queue
What is Circular Queue?
―It is similar to Queue.
―Principle is FIFO (First In First Out)
―last position is connected to the first position
in a circular queue that forms a circle
2
Components of Queue
Components of Queue
• Front: It is used to get the front element from the
Queue.
• Rear: It is used to get the rear element from the Queue.
• enQueue(value):
used to insert the new value in the Queue.
new element is always inserted from the rear end.
• deQueue():
deletes an element from the Queue.
It always takes place from the front end.
3
Enqueue
The steps of enqueue operation are given
below:
• Check whether the Queue is full or not.
• Initially the front and rear are set to -1. When
we insert the first element in a Queue, front
and rear both are set to 0.
• When we insert a new element, the rear gets
incremented, i.e., rear=rear+1.
4
Enqueue
Scenarios for inserting an element
• Two scenarios in which queue is not full
• If rear != max - 1, then rear will be
incremented to mod(maxsize) and the new
value will be inserted at the rear end of the
queue.
• If front != 0 and rear = max - 1, it means that
queue is not full, then set the value of rear to 0
and insert the new element there.
5
Enqueue
case in which the element cannot be inserted:
• When front ==0 && rear = max-1, which
means that front is at the first position of the
Queue and rear is at the last position of the
Queue.
• (rear+1)%max==front
6
Enqueue
Enqueue (int x)
if(front==-1 && rear==-1) // condition to check queue is empty
front=0;
rear=0;
queue[rear]=x;
else if((rear+1)%max==front) // condition to check queue is full
print Queue is overflow ;
else
rear=(rear+1)%max; // rear is incremented
queue[rear]=x; // assigning a value to the queue at the rear
position.
End if
End if
7
Dequeue
The steps of dequeue operation are given below:
• check whether the Queue is empty or not. If the
queue is empty, we cannot perform the dequeue
operation.
• When the element is deleted, the value of front
gets decremented by 1.
• If there is only one element left which is to be
deleted, then the front and rear are reset to -1.
8
Dequeue
Dequeue()
if((front==-1) && (rear==-1)) // condition to check queue is empty
print Queue is underflow;
else if(front==rear)
print queue[front];
front=-1;
rear=-1;
else
print queue[front];
front=(front+1)%max;
End if
End if
9
Display
Display()
if(isEmpty())
print("Queue is Empty");
else
for(int i=front;i<=rear;i++)
print(Queue[i] );
End if
10