Implement Priority Queue using Linked Lists.
Operations on Priority Queue :
- push(): This function is used to insert a new data into the queue.
- pop(): This function removes the element with the highest priority form the queue.
- peek() / top(): This function is used to get the highest priority element in the queue without removing it from the queue.
Priority Queues can be implemented using common data structures like arrays, linked-lists, heaps and binary trees.
The list is so created so that the highest priority element is always at the head of the list. The list is arranged in descending order of elements based on their priority. This allow us to remove the highest priority element in O(1) time. To insert an element we must traverse the list and find the proper position to insert the node so that the overall order of the priority queue is maintained. This makes the push() operation takes O(N) time. The pop() and peek() operations are performed in constant time.
PUSH(HEAD, DATA, PRIORITY)
Step 1: Create new node with DATA and PRIORITY
Step 2: Check if HEAD has lower priority. If true follow Steps 3-4 and end. Else goto Step 5.
Step 3: NEW -> NEXT = HEAD
Step 4: HEAD = NEW
Step 5: Set TEMP to head of the list
Step 6: While TEMP -> NEXT != NULL and TEMP -> NEXT -> PRIORITY > PRIORITY
Step 7: TEMP = TEMP -> NEXT
[END OF LOOP]
Step 8: NEW -> NEXT = TEMP -> NEXT
Step 9: TEMP -> NEXT = NEW
Step 10: End
Step 2: Set the head of the list to the next node in the list. HEAD = HEAD -> NEXT.
Step 3: Free the node at the head of the list
Step 4: End
Step 1: Return HEAD -> DATA
Step 2: End
Below is the implementation of the algorithm :
7 4 5 6
Time Complexities and Comparison with Binary Heap:
peek() push() pop() ----------------------------------------- Linked List | O(1) O(n) O(1) | Binary Heap | O(1) O(Log n) O(Log n)
- Priority Queue using doubly linked list
- Queue | Set 2 (Linked List Implementation)
- Difference between a Static Queue and a Singly Linked List
- Priority Queue | Set 1 (Introduction)
- Applications of Priority Queue
- Priority Queue in Python
- Double ended priority queue
- Priority Queue in C++ Standard Template Library (STL)
- How to implement stack using priority queue or heap?
- Why is Binary Heap Preferred over BST for Priority Queue?
- Circular Queue | Set 2 (Circular Linked List Implementation)
- Difference between Singly linked list and Doubly linked list
- Convert singly linked list into circular linked list
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.