合并 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* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
struct ListNode *head=NULL;
if(l1->val <= l2->val)
{
head=l1;
head->next = mergeTwoLists(l1->next, l2);
}
else
{
head=l2;
head->next = mergeTwoLists(l1, l2->next);
}
return head;
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) {
if(listsSize < 1)
{
return NULL;
}
if(1 == listsSize)
{
return lists[0];
}
struct ListNode *head = lists[0]; //首链表为数组第一个链表
int i;
for(i=1; i<listsSize; ++i) //遍历数组中所有链表
{
head = mergeTwoLists(head, lists[i]); //每个链表都与第一个链表合并归一
}
return head;
}
//==============================================================
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
//判断退出条件
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
struct ListNode *head=NULL;
if(l1->val <= l2->val)
{
head=l1;
head->next = mergeTwoLists(l1->next, l2); //递归调用后续节点
}
else
{
head=l2;
head->next = mergeTwoLists(l1, l2->next);
}
return head;
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) {
//判断特殊条件
if(listsSize < 1)
{
return NULL;
}
if(listsSize == 1)
{
return lists[0];
}
struct ListNode **newLists=lists;
int count=0;
int slice=0;
while(listsSize>1) //两两合并,逐步缩减为1
{
count=listsSize/2;//折半长度
slice=listsSize%2; //奇偶判断
for(int i=0; i<count; ++i) //两两合并归一
{
newLists[i] = mergeTwoLists(lists[2*i], lists[2*i+1]);
}
if(slice==1) //如果总长度为奇数,则最后一个链表无配对,需要挂上
{
newLists[count] = lists[listsSize-1];
}
listsSize = count + slice;//修改总长度
lists = newLists; //切换目标链表组
}
return lists[0];
}