Before you go ahead with understanding what Priority Queue is, we recommend you to first understand the concept and implementation of a Queue and Circular Queue.
If you are a Youtuber, and you want to keep a track of the video published by you which has the least number of views, then a priority queue or a min heap can help you.
A Heap is a binary tree in which the value of every parent node is less than it's child nodes. Hence the minimum value is always on the top.
A priority queue can be of two types:
In a priority queue, following factors come into play:
So now we will design our very own minimum priority queue using python list and object oriented concept.
Below are the algorithm steps:
Node
: The Node
class will be the element inserted in the priority queue. You can modify the Node
class as per your requirements.insert
: To add a new data element(Node
) in the priority queue.
delete
: To remove the element with least priority.size
: To check the size of the priority queue, in other words count the number of elements in the queue and return it.show
: To print all the priority queue elements.We will be using Python List for implementing queue data structure.
NOTE: We can also use the heapq
library to implement Priority Queue(heap) in python.
Try changing the code as you like. Click the button, to Run the code again.
NOTE: In the code above we haven't handled the duplicate node check, you should try to add that yourself.
/code/python/ds/priority-queue-in-python.php