Using Single Linked List
Using Single Linked List
To solve this problem by joining the front and rear ends of a queue to make the queue as a circular queue Circular queue is a linear data structure. It follows FIFO principle. In circular queue the last node is connected back to the first node to make a circle. Circular linked list fallow the First In First Out principle Elements are added at the rear end and the elements are deleted at front end of the queue Both the front and the rear pointers points to the beginning of the array. It is also called as Ring buffer. Items can inserted and deleted from a queue in O(1) time.
Circular Queue can be created in three ways they are Using single linked list Using double linked list Using arrays Using single linked list: It is an extension for the basic single linked list. In circular linked list Instead of storing a Null value in the last node of a single linked list, store the address of the 1st node (root) forms a circular linked list. Using circular linked list it is possible to directly traverse to the first node after reaching the last node. The following figure shows circular single linked list:
Using array In arrays the range of a subscript is 0 to n-1 where n is the maximum size. To make the array as a circular array by making the subscript 0 as the next address of the subscript n-1 by using the formula subscript = (subscript +1) % maximum size. In circular queue the front and rear pointer are updated by using the above formula. The following figure shows circular array:
Algorithm for Enqueue operation using array Step 1. start Step 2. if (front == (rear+1)%max) Print error circular queue overflow Step 3. else { rear = (rear+1)%max
Q[rear] = element; If (front == -1 ) f = 0; } Step 4. stop Algorithm for Dequeue operation using array Step 1. start Step 2. if ((front == rear) && (rear == -1)) Print error circular queue underflow Step 3. else { element = Q[front] If (front == rear) front=rear = -1 Else Front = (front + 1) % max } Step 4. stop