-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23.merge-k-sorted-lists.cpp
More file actions
41 lines (36 loc) · 994 Bytes
/
23.merge-k-sorted-lists.cpp
File metadata and controls
41 lines (36 loc) · 994 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
/**
* 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) {}
* };
*/
struct comp{
bool operator()(const ListNode* lhs, const ListNode* rhs)
{
return lhs->val > rhs->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, comp> p;
for(ListNode* node : lists)
if(node)
p.push(node);
ListNode* head = new ListNode();
ListNode* temp = head;
while(!p.empty()){
temp->next = p.top();
if(p.top()->next)
p.push(p.top()->next);
cout<<p.top()->val<<"\t";
p.pop();
temp = temp->next;
}
return head->next;
}
};