forked from geemaple/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
23.merge-k-sorted-lists.cpp
47 lines (39 loc) · 1.14 KB
/
23.merge-k-sorted-lists.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
40
41
42
43
44
45
46
47
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
static bool greater(ListNode *left, ListNode *right){
return left->val > right -> val;
}
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
vector<ListNode *> list;
ListNode head(0);
ListNode *cur = &head;
for(auto i = 0; i < lists.size(); ++i){
ListNode *node = lists[i];
if (node != NULL){
list.push_back(node);
}
}
make_heap(list.begin(), list.end(), greater);
while(!list.empty()){
ListNode *node = list.front();
pop_heap(list.begin(), list.end(), greater);
list.pop_back();
cur->next = node;
if (node->next){
list.push_back(node->next);
push_heap(list.begin(), list.end(), greater);
}
cur = cur->next;
}
return head.next;
}
};