-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsoln-1.cpp
32 lines (32 loc) · 847 Bytes
/
soln-1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* 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) {
ListNode * dummy = new ListNode(0);
ListNode * cur = dummy;
priority_queue<pair<int, ListNode *>> pq;
for(auto head : lists) {
if (head != nullptr) {
pq.push({-head->val, head});
}
}
while (!pq.empty()) {
ListNode * node = pq.top().second;
pq.pop();
cur->next = node;
cur = cur->next;
if (node->next != nullptr) {
pq.push({-node->next->val, node->next});
}
}
cur->next = nullptr;
return dummy->next;
}
};