Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created December 26, 2018 19:42
Show Gist options
  • Save kanrourou/58d1182d891138582bbaad3ea1b2afcd to your computer and use it in GitHub Desktop.
Save kanrourou/58d1182d891138582bbaad3ea1b2afcd to your computer and use it in GitHub Desktop.
/**
* 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