Implementation Dequeue Using Circular Array:
Dequeue or Double Ended Queue is a generalized version of Queue data structure that allows insert and delete at both ends.In previous post we had discussed introduction of dequeue. Now in this post we see how we implement dequeue Using circular array.
Operations on Dequeue:
Mainly the following four basic operations are performed on queue:
insertFront(): Adds an item at the front of Dequeue.
insertRear(): Adds an item at the rear of Dequeue.
deleteFront(): Deletes an item from front of Dequeue.
deleteRear(): Deletes an item from rear of Dequeue.
In addition to above operations, following operations are also supported
getFront(): Gets the front item from queue.
getRear(): Gets the last item from queue.
isEmpty(): Checks whether Dequeue is empty or not.
isFull(): Checks whether Dequeue is full or not.
Circular array implementation dequeue
For implementing dequeue, we need to keep track of two indices, front and rear. We enqueue(push) an item at the rear or the front end of queue and dequeue(pop) an item from both rear and front end.
1. Create an empty array ‘arr’ of size ‘n’
initialize front = -1 , rear = 0
Inserting First element in dequeue either front end or read end they both lead to the same result.
after insert Front Points = 0 and Rear points = 0
Insert Elements at Rear end
a). First we check dequeue if Full or Not b). IF Rear == Size-1 then reinitialize Rear = 0 ; Else increment Rear by '1' and push current key into Arr[ rear ] = key Front remain same.
Insert Elements at Front end
a). First we check dequeue if Full or Not b). IF Front == 0 || initial position, move Front to points last index of array front = size - 1 Else decremented front by '1' and push current key into Arr[ Front] = key Rear remain same.
Delete Element From Rear end
a). first Check dequeue is Empty or Not b). If dequeue has only one element front = -1 ; rear =-1 ; Else IF Rear points to the first index of array it's means we have to move rear to points last index [ now first inserted element at front end become rear end ] rear = size-1 ; Else || decrease rear by '1' rear = rear-1;
Delete Element From Front end
a). first Check dequeue is Empty or Not b). If dequeue has only one element front = -1 ; rear =-1 ; Else IF front points to the last index of the array it's means we have no more elements in array so we move front to points first index of array front = 0 ; Else || increment Front by '1' front = front+1;
Java Implementation Dequeue Using Circular Array:
insert element at rear end : 5 insert element at rear end : 10 get rear element : 10 After delete rear element new rear become : 5 inserting element at front end get front element : 15 After delete front element new front become : 5
Time Complexity: Time complexity of all operations like insertfront(), insertlast(), deletefront(), deletelast() is O(1).