forked from coderchen/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeKSortedLists.cpp
58 lines (48 loc) · 953 Bytes
/
MergeKSortedLists.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
#include <iostream>
#include <queue>
#include <algorithm>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
private:
ListNode* _merge(ListNode* l1, ListNode* l2) {
ListNode* head = nullptr;
ListNode** pp = &head;
while (l1 && l2) {
if (l1->val <= l2->val) {
*pp = l1;
pp = &l1->next;
l1 = l1->next;
} else {
*pp = l2;
pp = &l2->next;
l2 = l2->next;
}
*pp = nullptr;
}
if (l1) *pp = l1;
if (l2) *pp = l2;
return head;
}
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
std::queue<ListNode*> q;
std::for_each(lists.begin(), lists.end(),
[&q](ListNode* node) { q.push(node); });
while (q.size() > 1) {
ListNode* l1 = q.front();
q.pop();
ListNode* l2 = q.front();
q.pop();
q.push(_merge(l1, l2));
}
return q.empty() ? nullptr : q.front();
}
};
int main()
{
return 0;
}