Queue
Previously, we have seen how a stack works. In this blog, I want to give you some insights on another elementary data structure, queue. Queue works on First-In-First-Out (FIFO) principle. Queue can be modeled in real life by a line of customers waiting to pay the bill. The new customers are added at the end of the queue and the customer at the front of the queue comes out after paying the bill. Similar to the push and pop operation of stack, queue has enqueue and dequeue operation. Enqueue adds the element to the end of the queue while dequeue removes the first element from the queue.
Here, we implement a queue using an array Q [1…n]. Queue has its attribute, Q.head which points to the head of the queue. Also, Q.tail points to the next location at which the new element will be inserted. When Q.head == Q.tail then, we can infer that the queue is empty. The queue is full if Q.head = Q.tail + 1. Similar to stack, the queue underflows if we try to dequeue an empty queue and the queue overflows if we try to enqueue an element in the full queue.
Pseudocode: ENQUEUE(Q, x)
Q[Q.tail] = x
if Q.tail == Q.length //queue is made circular when all array space has been used
Q.tail = 1
else
Q.tail = Q.tail + 1
DEQUEUE(Q)
x = Q[Q.head]
if Q.head == Q.length
Q.head = 1 //when all the elements has been dequeue then Q.head points to first location
else
Q.head = Q.head + 1
return x
We can see that the both operations above are constant time operation i.e. the running time of both enqueue and dequeue operation is bounded by θ(1). Queue has an important application in breadth first search (BFS) where it is used to store the nodes which have been visited and remove the nodes which have been expanded. The main disadvantage of implementing queue using an array is that the array space should be defined for the maximum number of elements. If this space is not sufficient, then it is difficult to add more while if too much space is allocated then, there will be wastage of space.
To read about stack data structure, visit https://selfstudygeek.blogspot.com/2018/11/stack.html.
Reference:
Introduction to Algorithms by CLRS
Comments
Post a Comment