题目:
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
解题:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize){
if(listsSize == 0) return 0;
struct ListNode* min = 0;
int idx = 0;
int cnt = 0;
for (int i = 0; i < listsSize; i++)
{
if(lists[i] == 0)
{
cnt++;
if(cnt == listsSize) return 0;
}
else if (min == 0)
{
min = lists[i];
idx = i;
}
else if (lists[i] != 0 && lists[i]->val < min->val)
{
min = lists[i];
idx = i;
}
}
struct ListNode* ret = min;
struct ListNode** buf = &ret;
while (cnt != listsSize)
{
if (lists[idx] != 0) {
lists[idx] = lists[idx]->next;
}
min = 0;
cnt = 0;
for (int i = 0; i < listsSize; i++)
{
if (lists[i] == 0)
{
cnt++;
}
else if (min == 0)
{
min = lists[i];
idx = i;
}
else if (lists[i]->val < min->val)
{
min = lists[i];
idx = i;
}
}
buf[0]->next = min;
buf = &(buf[0]->next);
}
return ret;
}