104. Merge k Sorted Lists

合并k个已排序的链表

LintCode链接

题目描述

合并k个已排序的链表

样例

1
2
3
4
5
6
对于下面三个链表,输出-1->2->4->null
[
2->4->null,
null,
-1->null
],

思路

对于写过归并排序的人来说,题目比较简单,思路就是从k个链表中,找到当前最小的元素,插入到返回的链表中,并从被选择的链表中删除这元素

代码

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
class Solution {
public:
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
ListNode *mergeKLists(vector<ListNode *> &lists) {
// write your code here
ListNode *root = NULL, *back_node = NULL;

while (true)
{
int min = std::numeric_limits<int>::max();
vector<ListNode *>::iterator min_iter = lists.end();
for (auto iter = lists.begin(); iter != lists.end(); ++iter)
{
ListNode *cur_node = *iter;
if (cur_node != NULL && cur_node->val < min)
{
min = cur_node->val;
min_iter = iter;
}
}

if (min_iter == lists.end())
{
break;
}

ListNode *min_node = *min_iter;
if (root == NULL)
{
root = min_node;
back_node = min_node;
}
else
{
back_node->next = min_node;
back_node = min_node;
}

*min_iter = min_node->next;
min_node->next = NULL;
}

return root;
}
};