-
Notifications
You must be signed in to change notification settings - Fork 0
/
23.合并k个排序链表.cpp
65 lines (63 loc) · 1.18 KB
/
23.合并k个排序链表.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
/*
* @lc app=leetcode.cn id=23 lang=cpp
*
* [23] 合并K个排序链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// struct ListNode
// {
// int val;
// ListNode *next;
// ListNode(int x) : val(x), next(nullptr) {}
// };
// #include <vector>
// using namespace std;
class Solution
{
ListNode *Merge(ListNode *a, ListNode *b)
{
if (a == nullptr)
{
return b;
}
if (b == nullptr)
{
return a;
}
ListNode *res = nullptr;
if (a->val <= b->val)
{
res = a;
res->next = Merge(a->next, b);
}
else
{
res = b;
res->next = Merge(a, b->next);
}
return res;
}
public:
ListNode *mergeKLists(vector<ListNode *> &lists)
{
if (lists.size() == 0)
{
return nullptr;
}
ListNode *res = nullptr;
for (auto &&i : lists)
{
res = Merge(res, i);
}
return res;
}
};
// @lc code=end