What Is Priority Queue - Introduction To Priority Queue
What Is Priority Queue - Introduction To Priority Queue
As you know that in a max heap, the maximum element is the root node.
And it will remove the element which has maximum priority first. Thus, you
remove the root node from the queue. This removal creates an empty slot,
which will be further filled with new insertion. Then, it compares the newly
inserted element with all the elements inside the queue to maintain the
heap invariant.
This operation helps to return the maximum element from Max Heap or the
minimum element from Min Heap without deleting the node from the priority
queue.
The root node is the maximum element in a max heap, as you may know. It
will also remove the element with the highest priority first. As a result, the
root node is removed from the queue. This deletion leaves an empty space,
which will be filled with fresh insertions in the future. The heap invariant is
then maintained by comparing the newly inserted element to all other entries
in the queue.
Arrays
Linked list
Heap data
structure Binary
search tree
struct item {
int item;
int
priority;
}
enqueue(): This function is used to insert new data into the queue.
dequeue(): This function removes the element with the highest priority from
the queue.
peek()/top(): This function is used to get the highest priority element in
the queue without removing it from the queue.
Output
16
14
12
35 {
36 Node* temp = *head;
37 (*head) = (*head)->next;
38 free(temp);
39 }
40
41 // Function to push according to
priority
42 void push(Node** head, int d, int p)
43 {
44 Node* start = (*head);
45
46 // Create new Node
47 Node* temp = newNode(d, p);
48
49 // Special Case: The head of list
has
50 // lesser priority than new node
51 if ((*head)->priority < p) {
52
53 // Insert New Node before head
54 temp->next = *head;
55 (*head) = temp;
56 }
57 else {
58
59 // Traverse the list and find
a
60 // position to insert new node
61 while (start->next != NULL
62 && start->next->priority p) {
>
63 start = start->next;
64 }
65
66 // Either at the ends of the
list
67 // or at required position
68 temp->next = start->next;
69 start->next = temp;
70 }
71 }
72
73 // Function to check is list is empty
74 int isEmpty(Node** head) { return == NULL;
(*head) }
75
76 // Driver code
77 int main()
78 {
79
80 // Create a Priority Queue
81 // 7->4->5->6
82 Node* pq = newNode(4, 1);
83 push(&pq, 5, 2);
84 push(&pq, 6, 3);
85 push(&pq, 7, 0);
86
87 while (!isEmpty(&pq)) {
88 cout << " " <<
peek(&pq);
89 pop(&pq);
90 }
91 return 0;
92 }
Output
6 5 4 7
A Self-Balancing Binary Search Tree like AVL Tree, Red-Black Tree, etc. can
also be used to implement a priority queue. Operations like peek(), insert()
and delete() can be performed using BST.