generated from threeal/project-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsolution.cpp
39 lines (29 loc) · 780 Bytes
/
solution.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
33
34
35
36
37
38
39
#include <queue>
#include <vector>
class Solution {
public:
struct Compare {
bool operator()(ListNode* a, ListNode* b) {
return a->val > b->val;
}
};
ListNode* mergeKLists(std::vector<ListNode*>& lists) {
std::priority_queue<ListNode*, std::vector<ListNode*>, Compare> queue{};
for (const auto list : lists) {
if (list == nullptr) continue;
queue.push(list);
}
if (queue.empty()) return nullptr;
auto head{queue.top()};
queue.pop();
if (head->next != nullptr) queue.push(head->next);
auto node{head};
while (!queue.empty()) {
node->next = queue.top();
queue.pop();
if (node->next->next != nullptr) queue.push(node->next->next);
node = node->next;
}
return head;
}
};