题目描述:
对K个有序的链表进行合并,合并成一个有序的链表
该题目需要思考的问题:
1、如何将有序的多个链表合并成为一个链表。
解决该问题的思路:
1、首先对两个有序的链表进行归并;
2、由于该问题的解决方案就是其子问题的解决方案,再利用递归的思想进行多次归并。
具体的代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
//将K个有序的链表合并成为一个链表,并返回该链表
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
return partition(lists,0,lists.size()-1);
}
//递归对K个链表进行排序
ListNode* partition(vector<ListNode*>& Lists,int start,int end){
if(start==end) return Lists[start];
if(start<end){
int mid=(end-start)/2;
ListNode *l1=partition(Lists,start,start+mid);
ListNode *l2=partition(Lists,start+mid+1,end);
return mergeTwoLists(l1,l2);
}
return NULL;
}
//合并两个有序链表为一个链表
ListNode* mergeTwoLists(ListNode *l1,ListNode *l2){
if(l1==NULL) return l2;
if(l2==NULL) return l1;
if(l1->val>l2->val){
ListNode *temp=l2;
temp->next=mergeTwoLists(l1,l2->next);
return temp;
}
else{
ListNode *temp=l1;
temp->next=mergeTwoLists(l1->next,l2);
return temp;
}
}
};