/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
//分治两两合并
if(lists.size()<=0) return NULL;
return mergeK(lists,0,lists.size()-1);
}
ListNode * mergeK(vector<ListNode*>& lists,int l,int r){
if(l>r) return NULL;
if(l==r) return lists[l];
else{
int mid = (l+r)/2;
return mergeTwo(mergeK(lists,l,mid),mergeK(lists,mid+1,r));
}
}
ListNode * mergeTwo(ListNode * l1,ListNode * l2){
if(l1==NULL) return l2;
if(l2==NULL) return l1;
ListNode * p1=l1;
ListNode * p2=l2;
ListNode * head=NULL;
if(l1->val<l2->val){head=p1;p1=p1->next;}
else{head=p2;p2=p2->next;}
ListNode * cur=head;
while(p1!=NULL&& p2!=NULL){
if(p1->val<p2->val){cur->next=p1;p1=p1->next;}
else{cur->next=p2;p2=p2->next;}
cur = cur->next;
}
if(p1!=NULL) cur->next=p1;
if(p2!=NULL) cur->next=p2;
return head;
}
};
两两合并,最后再合并,就是多路归并,重复调用两个有序链表合并(解析见:https://mp.csdn.net/console/editor/html/108025779)