Title description:
Merge k sorted linked lists and return the merged sorted linked list. Please analyze and describe the complexity of the algorithm.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
Question Analysis :
First write a function that merges two ordered linked lists into one linked list, and use this function to merge all linked lists in lists into the first linked list in turn.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* merge(ListNode*l1,ListNode*l2){ //将两个链表合并的函数
if(l1==NULL&&l2!=NULL){ //如果两个链表有一个为空,那么返回另外一个。如果都为空,返回NULL。
return l2;
}
else if(l1!=NULL&&l2==NULL){
return l1;
}
else if(l1==NULL&&l2==NULL){
return NULL;
}
ListNode*ans,*p;
if(l1->val<=l2->val){ //处理首节点
ans=l1;
l1=l1->next;
}
else{
ans=l2;
l2=l2->next;
}
p=ans;
while(l1!=NULL&&l2!=NULL){ //每次从两个链表中取出一个结点放到结果链表当中
if(l1->val<=l2->val){
p->next=l1;
l1=l1->next;
p=p->next;
}
else{
p->next=l2;
l2=l2->next;
p=p->next;
}
}
while(l1!=NULL){ //两个while只执行一个,将长的那个链表的剩余结点放到结果链表中
p->next=l1;
l1=l1->next;
p=p->next;
}
while(l2!=NULL){
p->next=l2;
l2=l2->next;
p=p->next;
}
p->next=NULL; //将链表的结尾置为NULL;
return ans;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size()==0){ //如果lists为空,那么返回NULL;
return NULL;
}
ListNode*ans=lists[0];
for(int i=1;i<lists.size();i++){
ans=merge(ans,lists[i]); //处理所有的链表
}
return ans;
}
};