Created
December 26, 2018 19:42
-
-
Save kanrourou/58d1182d891138582bbaad3ea1b2afcd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for singly-linked list. | |
* struct ListNode { | |
* int val; | |
* ListNode *next; | |
* ListNode(int x) : val(x), next(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
ListNode* mergeKLists(vector<ListNode*>& lists) { | |
auto comp = [](const ListNode* n1, const ListNode* n2) | |
{ | |
return n1->val > n2->val; | |
}; | |
priority_queue<ListNode*, vector<ListNode*>, decltype(comp)> pq(comp); | |
for(const auto node : lists)if(node)pq.push(node); | |
ListNode* head = nullptr, *tail = nullptr; | |
while(pq.size()) | |
{ | |
auto curr = pq.top(); | |
pq.pop(); | |
if(!head) | |
{ | |
head = curr; | |
tail = curr; | |
} | |
else | |
{ | |
tail->next = curr; | |
tail = tail->next; | |
} | |
if(curr->next) | |
pq.push(curr->next); | |
} | |
return head; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment