{"id":3634,"date":"2021-08-06T11:27:28","date_gmt":"2021-08-06T11:27:28","guid":{"rendered":"https:\/\/www.prepbytes.com\/blog\/?p=3634"},"modified":"2022-12-13T11:31:42","modified_gmt":"2022-12-13T11:31:42","slug":"priority-queue-using-a-linked-list","status":"publish","type":"post","link":"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/","title":{"rendered":"Priority Queue using a Linked List"},"content":{"rendered":"<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644922320273-93.Prority%20using%20lined%20list_Artboard%206.png\" alt=\"\" \/><\/p>\n<h3>Introduction<\/h3>\n<p>The linked list is one of the most important concepts and data structures to learn while preparing for interviews. Having a good grasp of Linked Lists can be a huge plus point in a coding interview.<\/p>\n<\/p>\n<h3>Problem Statement<\/h3>\n<p>Here in this problem we will be implementing a priority queue using a linked list.<\/p>\n<h3>Problem Statement Understanding<\/h3>\n<p>There are 3 main operations in a priority queue:<\/p>\n<ul>\n<li><strong>push()<\/strong> &#8211; to insert a new element into the queue.<\/li>\n<li><strong>pop()<\/strong> &#8211; to remove the highest priority element from the queue.<\/li>\n<li><strong>peep()<\/strong> &#8211; to retrieve the highest priority element, without removing it from the queue. <\/li>\n<\/ul>\n<p>What we are going to do is, create a linked list, but with a few tweaks, the list will be created in such a way, that the highest priority element will always be the head of the linked list. That means the list will be sorted in the descending order of the elements based on their priority. By doing this, we can do the peek() operation in O(1) time.<\/p>\n<p>For the push() operation, we have to find a suitable position to insert the current node so that the overall order of the priority queue is maintained. This will take O(n) time. Let us have a look at the approaches. <\/p>\n<h3>Approach(push)<\/h3>\n<p>In the push function, we have to first find the suitable position for the value to be inserted. We have to traverse through the list and find the node which has a lower priority than the current node. This is going to maintain the decreasing order of the priority queue. <\/p>\n<h4>Algorithm<\/h4>\n<ul>\n<li>Create a new node.<\/li>\n<li>If the priority of the current node is greater than the head&#8217;s priority, then insert at the beginning and make the current node the head of the list.<\/li>\n<li>Else, find the appropriate position to insert the current node according to the descending order of their priorities. We can do this by traversing through the list.<\/li>\n<li>After the appropriate node is found i.e. the node whose priority is lesser than the new node\u2019s priority, store it in X, just for the sake of simplicity.<\/li>\n<li>Now, insert the new node just before X, as the new node\u2019s priority is greater than X. <\/li>\n<\/ul>\n<h3>Approach(pop)<\/h3>\n<p>In the pop function, we will increment the head as head -&gt; next. This will delete the head.<\/p>\n<h4>Algorithm<\/h4>\n<ul>\n<li>Create a new node temp and its value will be the head. <\/li>\n<li>Now, increment the head as head = head &#8211; &gt; next. This will delete the current node.<\/li>\n<li>Now, there is a memory leak. A memory leak happens when we remove the links of a node, but do not free it from the memory. Although the node is remove from the linked list, it still says in the memory. <\/li>\n<li>To remove the memory leak, we can use the free method free(temp)<\/li>\n<li>The free method remove the passed node from the memory.<\/li>\n<\/ul>\n<h3>Approach(peek)<\/h3>\n<p>The work of the peek function is to retrieve the highest priority element, without removing it from the queue. <\/p>\n<p>So, we will simply return the head -&gt; data , as the head will always contain the highest priority element. <\/p>\n<h4>Algorithm<\/h4>\n<ul>\n<li>Return head &#8211; &gt; data, as the head will always contain the highest priority element.<\/li>\n<\/ul>\n<h3>Dry Run<\/h3>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/08\/48_1-01.png\" alt=\"\" \/><\/p>\n<h3>Code Implementation<\/h3>\n\t\t\t\t\t\t<style>\r\n\t\t\t\t\r\n\t\t\t\t\t#tab_container_3636 {\r\n\toverflow:hidden;\r\n\tdisplay:block;\r\n\twidth:100%;\r\n\tborder:0px solid #ddd;\r\n\tmargin-bottom:30px;\r\n\t}\r\n\r\n#tab_container_3636 .tab-content{\r\n\tpadding:20px;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n\tmargin-top: 0px;\r\n\tbackground-color:#ffffff !important;\r\n\tcolor: #000000 !important;\r\n\tfont-size:16px !important;\r\n\tfont-family: Open Sans !important;\r\n\t\r\n\t\tborder: 1px solid #e6e6e6 !important;\r\n\t}\r\n#tab_container_3636 .wpsm_nav-tabs {\r\n    border-bottom: 0px solid #ddd;\r\n}\r\n#tab_container_3636 .wpsm_nav-tabs > li.active > a, #tab_container_3636 .wpsm_nav-tabs > li.active > a:hover, #tab_container_3636 .wpsm_nav-tabs > li.active > a:focus {\r\n\tcolor: #000000 !important;\r\n\tcursor: default;\r\n\tbackground-color: #ffffff !important;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n}\r\n\r\n#tab_container_3636 .wpsm_nav-tabs > li > a {\r\n    margin-right: 0px !important; \r\n    line-height: 1.42857143 !important;\r\n    border: 1px solid #d5d5d5 !important;\r\n    border-radius: 0px 0px 0 0 !important; \r\n\tbackground-color: #e8e8e8 !important;\r\n\tcolor: #000000 !important;\r\n\tpadding: 15px 18px 15px 18px !important;\r\n\ttext-decoration: none !important;\r\n\tfont-size: 14px !important;\r\n\ttext-align:center !important;\r\n\tfont-family: Open Sans !important;\r\n}\r\n#tab_container_3636 .wpsm_nav-tabs > li > a:focus {\r\noutline: 0px !important;\r\n}\r\n\r\n#tab_container_3636 .wpsm_nav-tabs > li > a:before {\r\n\tdisplay:none !important;\r\n}\r\n#tab_container_3636 .wpsm_nav-tabs > li > a:after {\r\n\tdisplay:none !important ;\r\n}\r\n#tab_container_3636 .wpsm_nav-tabs > li{\r\npadding:0px !important ;\r\nmargin:0px;\r\n}\r\n\r\n#tab_container_3636 .wpsm_nav-tabs > li > a:hover , #tab_container_3636 .wpsm_nav-tabs > li > a:focus {\r\n    color: #000000 !important;\r\n    background-color: #e8e8e8 !important;\r\n\tborder: 1px solid #d5d5d5 !important;\r\n\t\r\n}\r\n#tab_container_3636 .wpsm_nav-tabs > li > a .fa{\r\n\r\nmargin-right:5px !important;\r\n\r\nmargin-left:5px !important;\r\n\r\n\r\n}\r\n\r\n\t\t#tab_container_3636 .wpsm_nav-tabs a{\r\n\t\t\tbackground-image: none;\r\n\t\t\tbackground-position: 0 0;\r\n\t\t\tbackground-repeat: repeat-x;\r\n\t\t}\r\n\t\t\t\r\n\r\n\r\n#tab_container_3636 .wpsm_nav-tabs > li {\r\n    float: left;\r\n    margin-bottom: -1px !important;\r\n\tmargin-right:0px !important; \r\n}\r\n\r\n\r\n#tab_container_3636 .tab-content{\r\noverflow:hidden !important;\r\n}\r\n\r\n\r\n@media (min-width: 769px) {\r\n\r\n\t#tab_container_3636 .wpsm_nav-tabs > li{\r\n\t\tfloat:left !important ;\r\n\t\t\t\tmargin-right:-1px !important;\r\n\t\t\t\t\t}\r\n\t#tab_container_3636 .wpsm_nav-tabs{\r\n\t\tfloat:none !important;\r\n\t\tmargin:0px !important;\r\n\t}\r\n\r\n\t#tab_container_3636 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_3636 .wpsm_nav{\r\n\t\t\t}\r\n\r\n}\r\n\r\n\r\n\r\n@media (max-width: 768px) {\r\n\t#tab_container_3636 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_3636 .wpsm_nav{\r\n\t\t\t}\r\n}\r\n\r\n\r\n\t.wpsm_nav-tabs li:before{\r\n\t\tdisplay:none !important;\r\n\t}\r\n\r\n\t@media (max-width: 768px) {\r\n\t\t\t\t\r\n\t\t\t\t.wpsm_nav-tabs{\r\n\t\t\tmargin-left:0px !important;\r\n\t\t\tmargin-right:0px !important; \r\n\t\t\t\r\n\t\t}\r\n\t\t\t\t#tab_container_3636 .wpsm_nav-tabs > li{\r\n\t\t\tfloat:none !important;\r\n\t\t}\r\n\t\t\t\r\n\t}\t\t\t\t<\/style>\r\n\t\t\t\t<div id=\"tab_container_3636\" >\r\n\t \r\n\t\t\t\t\t<ul class=\"wpsm_nav wpsm_nav-tabs\" role=\"tablist\" id=\"myTab_3636\">\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  class=\"active\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_3636_1\" aria-controls=\"tabs_desc_3636_1\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>C<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_3636_2\" aria-controls=\"tabs_desc_3636_2\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>C++<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_3636_3\" aria-controls=\"tabs_desc_3636_3\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Java<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_3636_4\" aria-controls=\"tabs_desc_3636_4\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Python<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\t\t\t\t <\/ul>\r\n\r\n\t\t\t\t\t  <!-- Tab panes -->\r\n\t\t\t\t\t  <div class=\"tab-content\" id=\"tab-content_3636\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane  in active \" id=\"tabs_desc_3636_1\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"c\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"c\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n\/\/ priority Node\r\ntypedef struct node {\r\n   int data;\r\n   int priority;\r\n   struct node* next;\r\n} Node;\r\nNode* newNode(int d, int p) {\r\n   Node* temp = (Node*)malloc(sizeof(Node));\r\n   temp->data = d;\r\n   temp->priority = p;\r\n   temp->next = NULL;\r\n   return temp;\r\n}\r\nint peek(Node** head) {\r\n   return (*head)->data;\r\n}\r\nvoid pop(Node** head) {\r\n   Node* temp = *head;\r\n   (*head) = (*head)->next;\r\n   free(temp);\r\n}\r\nvoid push(Node** head, int d, int p) {\r\n   Node* start = (*head);\r\n   Node* temp = newNode(d, p);\r\n   if ((*head)->priority > p) {\r\n      temp->next = *head;\r\n      (*head) = temp;\r\n   } else {\r\n      while (start->next != NULL &&\r\n      start->next->priority < p) {\r\n         start = start->next;\r\n      }\r\n      \/\/ Either at the ends of the list\r\n      \/\/ or at required position\r\n      temp->next = start->next;\r\n      start->next = temp;\r\n   }\r\n}\r\n\/\/ Function to check the queue is empty\r\nint isEmpty(Node** head) {\r\n   return (*head) == NULL;\r\n}\r\n\/\/ main function\r\nint main() {\r\n   Node* pq = newNode(7, 1);\r\n   push(&pq, 1, 2);\r\n   push(&pq, 3, 3);\r\n   push(&pq, 2, 0);\r\n   while (!isEmpty(&pq)) {\r\n      printf(\"%d \", peek(&pq));\r\n      pop(&pq);\r\n   }\r\n   return 0;\r\n}\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_3636_2\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"cpp\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\n#include <bits stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef struct node\r\n{\r\n    int data;\r\n\r\n    int priority;\r\n \r\n    struct node* next;\r\n \r\n} Node;\r\n\r\nNode* newNode(int d, int p)\r\n{\r\n    Node* temp = (Node*)malloc(sizeof(Node));\r\n    temp->data = d;\r\n    temp->priority = p;\r\n    temp->next = NULL;\r\n \r\n    return temp;\r\n}\r\n\r\nint peek(Node** head)\r\n{\r\n    return (*head)->data;\r\n}\r\n\r\nvoid pop(Node** head)\r\n{\r\n    Node* temp = *head;\r\n    (*head) = (*head)->next;\r\n    free(temp);\r\n}\r\n\r\nvoid push(Node** head, int d, int p)\r\n{\r\n    Node* start = (*head);\r\n\r\n    Node* temp = newNode(d, p);\r\n\r\n    if ((*head)->priority > p)\r\n    {\r\n\r\n        temp->next = *head;\r\n        (*head) = temp;\r\n    }\r\n    else\r\n    {\r\n\r\n        while (start->next != NULL &&\r\n            start->next->priority < p)\r\n        {\r\n            start = start->next;\r\n        }\r\n\r\n        temp->next = start->next;\r\n        start->next = temp;\r\n    }\r\n}\r\n\r\nint isEmpty(Node** head)\r\n{\r\n    return (*head) == NULL;\r\n}\r\n\r\nint main()\r\n{\r\n\r\n    Node* pq = newNode(3, 1);\r\n    push(&pq, 2, 2);\r\n    push(&pq, 1, 5);\r\n    push(&pq, 4, 4);\r\n \r\n    while (!isEmpty(&pq))\r\n    {\r\n        cout << \" \" << peek(&pq);\r\n        pop(&pq);\r\n    }\r\n    return 0;\r\n}\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\r\n\r\n\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_3636_3\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"java\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\nimport java.util.* ;\r\n\r\npublic class Solution\r\n{\r\n    \r\nstatic class Node {\r\n    int data;\r\n    \r\n\r\n    int priority;\r\n    \r\n    Node next;\r\n    \r\n}\r\n\r\nstatic Node node = new Node();\r\n    \r\n\r\nstatic Node newNode(int d, int p)\r\n{\r\n    Node temp = new Node();\r\n    temp.data = d;\r\n    temp.priority = p;\r\n    temp.next = null;\r\n    \r\n    return temp;\r\n}\r\n\r\nstatic int peek(Node head)\r\n{\r\n    return (head).data;\r\n}\r\n\r\nstatic Node pop(Node head)\r\n{\r\n    Node temp = head;\r\n    (head) = (head).next;\r\n    return head;\r\n}\r\n\r\nstatic Node push(Node head, int d, int p)\r\n{\r\n    Node start = (head);\r\n    \r\n\r\n    Node temp = newNode(d, p);\r\n\r\n    if ((head).priority > p) {\r\n    \r\n\r\n        temp.next = head;\r\n        (head) = temp;\r\n    }\r\n    else {\r\n\r\n        while (start.next != null &&\r\n            start.next.priority < p) {\r\n            start = start.next;\r\n        }\r\n\r\n        temp.next = start.next;\r\n        start.next = temp;\r\n    }\r\n    return head;\r\n}\r\n    \r\n\r\nstatic int isEmpty(Node head)\r\n{\r\n    return ((head) == null)?1:0;\r\n}\r\n    \r\n\r\npublic static void main(String args[])\r\n{\r\n    Node pq = newNode(3, 1);\r\n    pq =push(pq, 2, 2);\r\n    pq =push(pq, 1, 5);\r\n    pq =push(pq, 4, 4);\r\n    while (isEmpty(pq)==0) {\r\n        System.out.printf(\"%d \", peek(pq));\r\n        pq=pop(pq);\r\n    }\r\n}\r\n}\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\r\n\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_3636_4\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"Python\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"Python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\nclass PriorityQueueNode:\r\n    \r\n    def __init__(self, value, pr):\r\n        \r\n        self.data = value\r\n        self.priority = pr\r\n        self.next = None\r\n        \r\nclass PriorityQueue:\r\n    \r\n    def __init__(self):\r\n        \r\n        self.front = None\r\n        \r\n    def isEmpty(self):\r\n        \r\n        return True if self.front == None else False\r\n    \r\n    def push(self, value, priority):\r\n        \r\n        if self.isEmpty() == True:\r\n            \r\n            self.front = PriorityQueueNode(value,\r\n                                        priority)\r\n            \r\n            return 1\r\n            \r\n        else:\r\n            \r\n            if self.front.priority > priority:\r\n                \r\n                newNode = PriorityQueueNode(value, priority)\r\n                newNode.next = self.front\r\n                self.front = newNode\r\n                return 1\r\n                \r\n            else:\r\n                \r\n                temp = self.front\r\n                while temp.next:\r\n                    \r\n                    if priority <= temp.next.priority:\r\n                        break\r\n                    \r\n                    temp = temp.next\r\n                \r\n                newNode = PriorityQueueNode(value,\r\n                                            priority)\r\n                newNode.next = temp.next\r\n                temp.next = newNode\r\n                return 1\r\n    \r\n    def pop(self):\r\n        \r\n        if self.isEmpty() == True:\r\n            return\r\n        \r\n        else:\r\n            \r\n            self.front = self.front.next\r\n            return 1\r\n\r\n    def peek(self):\r\n        \r\n        if self.isEmpty() == True:\r\n            return\r\n        else:\r\n            return self.front.data\r\n            \r\n    def traverse(self):\r\n        \r\n        if self.isEmpty() == True:\r\n            return \"Queue is Empty!\"\r\n        else:\r\n            temp = self.front\r\n            while temp:\r\n                print(temp.data, end = \" \")\r\n                temp = temp.next\r\n\r\nif __name__ == \"__main__\":\r\n    \r\n    pq = PriorityQueue()\r\n    pq.push(3, 1)\r\n    pq.push(2, 2)\r\n    pq.push(1, 5)\r\n    pq.push(4, 4)\r\n    pq.traverse()\r\n    pq.pop()\r\n\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t <\/div>\r\n\t\t\t\t\t \r\n\t\t\t\t <\/div>\r\n <script>\r\n\t\tjQuery(function () {\r\n\t\t\tjQuery('#myTab_3636 a:first').tab('show')\r\n\t\t});\r\n\t\t\r\n\t\t\t\tjQuery(function(){\r\n\t\t\tvar b=\"fadeIn\";\r\n\t\t\tvar c;\r\n\t\t\tvar a;\r\n\t\t\td(jQuery(\"#myTab_3636 a\"),jQuery(\"#tab-content_3636\"));function d(e,f,g){\r\n\t\t\t\te.click(function(i){\r\n\t\t\t\t\ti.preventDefault();\r\n\t\t\t\t\tjQuery(this).tab(\"show\");\r\n\t\t\t\t\tvar h=jQuery(this).data(\"easein\");\r\n\t\t\t\t\tif(c){c.removeClass(a);}\r\n\t\t\t\t\tif(h){f.find(\"div.active\").addClass(\"animated \"+h);a=h;}\r\n\t\t\t\t\telse{if(g){f.find(\"div.active\").addClass(\"animated \"+g);a=g;}else{f.find(\"div.active\").addClass(\"animated \"+b);a=b;}}c=f.find(\"div.active\");\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\r\n\t\tfunction do_resize(){\r\n\r\n\t\t\tvar width=jQuery( '.tab-content .tab-pane iframe' ).width();\r\n\t\t\tvar height=jQuery( '.tab-content .tab-pane iframe' ).height();\r\n\r\n\t\t\tvar toggleSize = true;\r\n\t\t\tjQuery('iframe').animate({\r\n\t\t\t    width: toggleSize ? width : 640,\r\n\t\t\t    height: toggleSize ? height : 360\r\n\t\t\t  }, 250);\r\n\r\n\t\t\t  toggleSize = !toggleSize;\r\n\t\t}\r\n\r\n\r\n\t<\/script>\r\n\t\t\t\t\r\n\t\t\t\n<h4>Output<\/h4>\n<p>3 2 4 1<\/p>\n<h4>Time Complexity<\/h4>\n<p><strong>peek()<\/strong> &#8211; O(1)<br \/>\n<strong>push()<\/strong> &#8211; O(n), as list traversal is needed.<br \/>\n<strong>pop()<\/strong> &#8211; O(1)<\/p>\n<p>[forminator_quiz id=&#8221;3637&#8243;]<\/p>\n<p>So, in this article, we have tried to explain the most efficient approach to implement a priority queue using a linked list. This is a very interesting way to implement a priority queue, and that is what makes this problem an important one for coding interviews. If you want to solve more questions on Linked List, which are curated by our expert mentors at PrepBytes, you can follow this link <a href=\"https:\/\/mycode.prepbytes.com\/interview-coding\/practice\/linked-list\">Linked List<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction The linked list is one of the most important concepts and data structures to learn while preparing for interviews. Having a good grasp of Linked Lists can be a huge plus point in a coding interview. Problem Statement Here in this problem we will be implementing a priority queue using a linked list. Problem [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[128],"tags":[],"class_list":["post-3634","post","type-post","status-publish","format-standard","hentry","category-queues"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.8 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Learn to use Priority Queue Using Linked List in C++ and Java<\/title>\n<meta name=\"description\" content=\"This blog explains the most efficient approach to implement a priority queue using a linked list. This is a very interesting way to implement a priority queue.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Learn to use Priority Queue Using Linked List in C++ and Java\" \/>\n<meta property=\"og:description\" content=\"This blog explains the most efficient approach to implement a priority queue using a linked list. This is a very interesting way to implement a priority queue.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/\" \/>\n<meta property=\"og:site_name\" content=\"PrepBytes Blog\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/prepbytes0211\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-08-06T11:27:28+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-12-13T11:31:42+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644922320273-93.Prority%20using%20lined%20list_Artboard%206.png\" \/>\n<meta name=\"author\" content=\"PrepBytes\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"PrepBytes\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/\"},\"author\":{\"name\":\"PrepBytes\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/39fcf072e04987f16796546f2ca83c2e\"},\"headline\":\"Priority Queue using a Linked List\",\"datePublished\":\"2021-08-06T11:27:28+00:00\",\"dateModified\":\"2022-12-13T11:31:42+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/\"},\"wordCount\":648,\"commentCount\":0,\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644922320273-93.Prority%20using%20lined%20list_Artboard%206.png\",\"articleSection\":[\"Queues\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/\",\"url\":\"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/\",\"name\":\"Learn to use Priority Queue Using Linked List in C++ and Java\",\"isPartOf\":{\"@id\":\"http:\/\/43.205.93.38\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644922320273-93.Prority%20using%20lined%20list_Artboard%206.png\",\"datePublished\":\"2021-08-06T11:27:28+00:00\",\"dateModified\":\"2022-12-13T11:31:42+00:00\",\"description\":\"This blog explains the most efficient approach to implement a priority queue using a linked list. This is a very interesting way to implement a priority queue.\",\"breadcrumb\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#primaryimage\",\"url\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644922320273-93.Prority%20using%20lined%20list_Artboard%206.png\",\"contentUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644922320273-93.Prority%20using%20lined%20list_Artboard%206.png\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/43.205.93.38\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Queues\",\"item\":\"https:\/\/prepbytes.com\/blog\/category\/queues\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Priority Queue using a Linked List\"}]},{\"@type\":\"WebSite\",\"@id\":\"http:\/\/43.205.93.38\/#website\",\"url\":\"http:\/\/43.205.93.38\/\",\"name\":\"PrepBytes Blog\",\"description\":\"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING\",\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"http:\/\/43.205.93.38\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"http:\/\/43.205.93.38\/#organization\",\"name\":\"Prepbytes\",\"url\":\"http:\/\/43.205.93.38\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"contentUrl\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"width\":160,\"height\":160,\"caption\":\"Prepbytes\"},\"image\":{\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/prepbytes0211\/\",\"https:\/\/www.instagram.com\/prepbytes\/\",\"https:\/\/www.linkedin.com\/company\/prepbytes\/\",\"https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA\"]},{\"@type\":\"Person\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/39fcf072e04987f16796546f2ca83c2e\",\"name\":\"PrepBytes\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/850669d326db1e1531f04db0c63145d941c2a26792aaeee226a9e6675b0ac698?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/850669d326db1e1531f04db0c63145d941c2a26792aaeee226a9e6675b0ac698?s=96&d=mm&r=g\",\"caption\":\"PrepBytes\"},\"url\":\"https:\/\/prepbytes.com\/blog\/author\/prepbytes\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Learn to use Priority Queue Using Linked List in C++ and Java","description":"This blog explains the most efficient approach to implement a priority queue using a linked list. This is a very interesting way to implement a priority queue.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/","og_locale":"en_US","og_type":"article","og_title":"Learn to use Priority Queue Using Linked List in C++ and Java","og_description":"This blog explains the most efficient approach to implement a priority queue using a linked list. This is a very interesting way to implement a priority queue.","og_url":"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/","og_site_name":"PrepBytes Blog","article_publisher":"https:\/\/www.facebook.com\/prepbytes0211\/","article_published_time":"2021-08-06T11:27:28+00:00","article_modified_time":"2022-12-13T11:31:42+00:00","og_image":[{"url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644922320273-93.Prority%20using%20lined%20list_Artboard%206.png","type":"","width":"","height":""}],"author":"PrepBytes","twitter_card":"summary_large_image","twitter_misc":{"Written by":"PrepBytes","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#article","isPartOf":{"@id":"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/"},"author":{"name":"PrepBytes","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/39fcf072e04987f16796546f2ca83c2e"},"headline":"Priority Queue using a Linked List","datePublished":"2021-08-06T11:27:28+00:00","dateModified":"2022-12-13T11:31:42+00:00","mainEntityOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/"},"wordCount":648,"commentCount":0,"publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644922320273-93.Prority%20using%20lined%20list_Artboard%206.png","articleSection":["Queues"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/","url":"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/","name":"Learn to use Priority Queue Using Linked List in C++ and Java","isPartOf":{"@id":"http:\/\/43.205.93.38\/#website"},"primaryImageOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#primaryimage"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644922320273-93.Prority%20using%20lined%20list_Artboard%206.png","datePublished":"2021-08-06T11:27:28+00:00","dateModified":"2022-12-13T11:31:42+00:00","description":"This blog explains the most efficient approach to implement a priority queue using a linked list. This is a very interesting way to implement a priority queue.","breadcrumb":{"@id":"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#primaryimage","url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644922320273-93.Prority%20using%20lined%20list_Artboard%206.png","contentUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644922320273-93.Prority%20using%20lined%20list_Artboard%206.png"},{"@type":"BreadcrumbList","@id":"https:\/\/prepbytes.com\/blog\/priority-queue-using-a-linked-list\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/43.205.93.38\/"},{"@type":"ListItem","position":2,"name":"Queues","item":"https:\/\/prepbytes.com\/blog\/category\/queues\/"},{"@type":"ListItem","position":3,"name":"Priority Queue using a Linked List"}]},{"@type":"WebSite","@id":"http:\/\/43.205.93.38\/#website","url":"http:\/\/43.205.93.38\/","name":"PrepBytes Blog","description":"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING","publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/43.205.93.38\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"http:\/\/43.205.93.38\/#organization","name":"Prepbytes","url":"http:\/\/43.205.93.38\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/","url":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","contentUrl":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","width":160,"height":160,"caption":"Prepbytes"},"image":{"@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/prepbytes0211\/","https:\/\/www.instagram.com\/prepbytes\/","https:\/\/www.linkedin.com\/company\/prepbytes\/","https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA"]},{"@type":"Person","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/39fcf072e04987f16796546f2ca83c2e","name":"PrepBytes","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/850669d326db1e1531f04db0c63145d941c2a26792aaeee226a9e6675b0ac698?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/850669d326db1e1531f04db0c63145d941c2a26792aaeee226a9e6675b0ac698?s=96&d=mm&r=g","caption":"PrepBytes"},"url":"https:\/\/prepbytes.com\/blog\/author\/prepbytes\/"}]}},"_links":{"self":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/3634","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/comments?post=3634"}],"version-history":[{"count":4,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/3634\/revisions"}],"predecessor-version":[{"id":8067,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/3634\/revisions\/8067"}],"wp:attachment":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/media?parent=3634"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/categories?post=3634"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/tags?post=3634"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}