/
Merge_k_Sorted_Lists.cpp
81 lines (77 loc) · 2.27 KB
/
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// first recursion
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
// special cases
if (lists.empty()) return NULL;
if (lists.size() == 1) return lists[0];
// recursion
if (lists.size() > 2) {
ListNode* first = lists.back();
lists.pop_back();
ListNode* second = mergeKLists(lists);
vector<ListNode*> two;
two.push_back(first);
two.push_back(second);
return mergeKLists(two);
}
// merge 2 lists
ListNode* first = lists[0];
ListNode* second = lists[1];
if (!first && !second) return NULL;
if (first && !second) return first;
if (!first && second) return second;
ListNode* newNode = new ListNode(0);
ListNode* result = newNode;
while (first && second) {
if (first->val < second -> val) {
newNode -> next = first;
first = first->next;
} else {
newNode -> next = second;
second = second->next;
}
newNode = newNode->next;
}
newNode->next = first ? first : second;
return result->next;
}
};
// second use heap
struct compare {
bool operator()(const ListNode* a, const ListNode* b) {
return a->val > b->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, compare> minHeap;
// create min heap
for (int i = 0; i < lists.size(); i++) {
if (lists[i]) {
minHeap.push(lists[i]);
}
}
ListNode* dummyNode = new ListNode(0);
ListNode* currentNode = dummyNode;
while (!minHeap.empty()) {
ListNode* currentMin = minHeap.top();
minHeap.pop();
currentNode->next = currentMin;
if (currentMin->next) {
minHeap.push(currentMin->next);
}
currentNode = currentNode->next;
}
return dummyNode->next;
}
};