Open In App

Priority Queue using Linked List

Last Updated : 11 Feb, 2025
Comments
Improve
Suggest changes
37 Likes
Like
Report

Implement Priority Queue using Linked Lists. The Linked List should be so created so that the highest priority ( priority is assigned from 0 to n-1 where n is the number of elements, where 0 means the highest priority and n-1 being the least ) element is always at the head of the list. The list is arranged in descending order of elements based on their priority. The Priority Queue should have the below functions

  • push(): This function is used to insert a new data into the queue.
  • pop(): 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.

Examples:

Input: Values = 4 (priority = 1), 5 (priority = 2), 6 (priority = 3), 7 (priority = 0)
Output: 7 4 5 6
Explanation: Values get peeked and popped according to their priority in descending order.

This approach manages a priority queue using a linked list. The PUSH operation inserts nodes in order of priority, ensuring the highest priority node is always at the head. The POP operation removes the highest priority node, while PEEK returns the data of the highest priority node without removing it.

Follow these steps to solve the problem

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

POP(HEAD):

  • Step 1: Set the head of the list to the next node in the list. HEAD = HEAD -> NEXT. 
  • Step 2: Free the node at the head of the list 
  • Step 3: End

PEEK(HEAD): 

  • Step 1: Return HEAD -> DATA 
  • Step 2: End
C++
C Java Python C# JavaScript

Output
7 4 5 6

Time Complexity: push() -> O(n) , To insert an element we must traverse the list and find the proper position to insert the node . This makes the push() operation takes O(n) time.

pop -> O(1), as it is performed in constant time.

peek -> O(1), as it is performed in constant time.

Space Complexity: O(n), as we are making a List of size n


Next Article

Similar Reads