-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0023-merge-k-sorted-lists.cpp
More file actions
52 lines (51 loc) · 1.39 KB
/
0023-merge-k-sorted-lists.cpp
File metadata and controls
52 lines (51 loc) · 1.39 KB
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
#include <vector>
using namespace std;
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) {}
};
class Solution
{
public:
ListNode *mergeKLists(vector<ListNode *> &lists)
{
ListNode *res_head = nullptr;
ListNode *res_tail = res_head;
int i, min_index, n = lists.size();
bool all_null = true;
while (true)
{
all_null = true;
i = 0;
min_index = -1;
while (i < n)
{
if (lists[i] != nullptr)
{
all_null = false;
if (min_index == -1 || lists[min_index]->val > lists[i]->val)
min_index = i;
}
i++;
}
if (all_null)
break;
// if all_null is false then min_index is guaranteed to have a value >= 0
if (res_head == nullptr)
{
res_head = res_tail = new ListNode(lists[min_index]->val);
}
else
{
res_tail->next = new ListNode(lists[min_index]->val);
res_tail = res_tail->next;
}
lists[min_index] = lists[min_index]->next;
}
return res_head;
}
};