-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_k_sorted_lists_23.cpp
70 lines (64 loc) · 1.22 KB
/
merge_k_sorted_lists_23.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
#include"stdafx.h"
#include<iostream>
#include<vector>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* mergeKLists(vector<ListNode*>& lists)
{
vector<ListNode*> nodes_vec;
ListNode *result_list = NULL, *result_head = NULL;
for (int i = 0; i < lists.size(); i++)
{
nodes_vec.push_back(lists[i]);
}
while (true)
{
bool is_finish = true;
for (int i = 0; i < nodes_vec.size(); i++)
{
if (nodes_vec[i] != NULL)
{
is_finish = false;
break;
}
}
if (is_finish)
{
break;
}
int min_val = INT_MAX;
int min_idx = -1;
for (int i = 0; i < nodes_vec.size(); i++)
{
if (nodes_vec[i] && nodes_vec[i]->val < min_val)
{
min_val = nodes_vec[i]->val;
min_idx = i;
}
}
if (result_head == NULL)
{
result_head = nodes_vec[min_idx];
nodes_vec[min_idx] = nodes_vec[min_idx]->next;
result_list = result_head;
}
else
{
result_list->next = nodes_vec[min_idx];
result_list = result_list->next;
nodes_vec[min_idx] = nodes_vec[min_idx]->next;
}
}
return result_head;
}
int main()
{
vector<ListNode*> lst_vec = { new ListNode(2) , new ListNode(1), new ListNode(2) };
mergeKLists(lst_vec);
return 0;
}