-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path023.cpp
More file actions
46 lines (43 loc) · 953 Bytes
/
023.cpp
File metadata and controls
46 lines (43 loc) · 953 Bytes
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
40
41
42
43
44
45
46
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <priority_queue>
typedef struct {
bool operator() (const ListNode *l, const ListNode *r)
{
return l->val > r->val;
}
} Comp;
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *>& lists) {
priority_queue<ListNode *, std::vector<ListNode *>, Comp> pq;
vector<ListNode *> nodes;
for (int i = 0; i < lists.size(); ++i) {
if (lists[i]) {
pq.push(lists[i]);
}
}
while (!pq.empty()) {
ListNode *n = pq.top();
nodes.push_back(n);
pq.pop();
if (n->next) {
pq.push(n->next);
}
}
if (nodes.empty()) {
return NULL;
}
for (int i = 0; i < nodes.size() - 1; ++i) {
nodes[i]->next = nodes[i + 1];
}
nodes[nodes.size() - 1]->next = NULL;
return nodes[0];
}
};