-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23.cpp
More file actions
42 lines (35 loc) · 1016 Bytes
/
23.cpp
File metadata and controls
42 lines (35 loc) · 1016 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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
struct cmp
{
bool operator()(const ListNode* l, const ListNode* r) const
{
return l->val > r->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, cmp> pq;
for(ListNode* l : lists){
if(l != nullptr) pq.push(l);
}
ListNode* sol = new ListNode();
ListNode* f = sol;
while(!pq.empty()){
ListNode* p = pq.top(); pq.pop();
sol->next = new ListNode(p->val);
sol = sol->next;
if(p->next != nullptr) pq.push(p->next);
}
return f->next;
}
};