题目描述:
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
之前进行过合并两个排序链表的做法,在合并k个排序链表的时候,逐步将前两个链表合并成新的排序链表,再向后不断延伸,最终合并所有的排序链表。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if (!l1)
return l2;
if (!l2)
return l1;
if (l1->val<l2->val){
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else{
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}//合并两个排序链表的做法
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize){
if(listsSize==0||lists==NULL)
{
return NULL;
}
struct ListNode *p= lists[0];
for(int i=1;i<listsSize;i++)
{
p=mergeTwoLists(p,lists[i]);
}
return p;
}//逐步合并链表