Advertisement
nikunjsoni

23

Mar 20th, 2021
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11.  
  12.  
  13.  
  14. class Solution {
  15. public:
  16.    
  17.     struct compare {
  18.         bool operator()(const ListNode* l, const ListNode* r) {
  19.             return l->val > r->val;
  20.         }
  21.     };
  22.    
  23.     ListNode* mergeKLists(vector<ListNode*>& lists) {
  24.         priority_queue<ListNode *, vector<ListNode *>, compare> pq;
  25.         ListNode *dummy = new ListNode(0);
  26.         for(auto head:lists) if(head) pq.push(head);
  27.        
  28.         ListNode* curr = dummy;
  29.         while(!pq.empty()){
  30.             ListNode *tmp = pq.top();
  31.             curr->next = tmp;
  32.             pq.pop();
  33.             if(tmp->next) pq.push(tmp->next);
  34.             curr = curr->next;
  35.         }
  36.         return dummy->next;
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement