23、Merge k Sorted Lists
合并k个排序链表
合并k个排序链表,并且返回合并后的排序链表。尝试分析和描述其复杂度。样例
给出3个排序链表[2->4->null,null,-1->null],返回 -1->2->4->null
分析:
也就是合并2个排序链表的扩展。
我的代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.empty())return NULL;
for(int i=1;i<lists.size();i++)//直接相加
lists[0]=mergeTwoLists(lists[0],lists[i]);
return lists[0];
}
ListNode* mergeTwoLists(ListNode* l1,ListNode* l2)
{//递归形式
if(!l1)return l2;
if(!l2)return l1;
if(l1->val>l2->val)
{
l2->next=mergeTwoLists(l1,l2->next);
return l2;
}
else
{
l1->next=mergeTwoLists(l1->next,l2);
return l1;
}
}
};
经典代码:
ListNode *mergeKLists(vector<ListNode *> &lists) {
if(lists.empty()){
return nullptr;
}
while(lists.size() > 1){//归并形式,两两相加
lists.push_back(mergeTwoLists(lists[0], lists[1]));
lists.erase(lists.begin());
lists.erase(lists.begin());
}
return lists.front();
}
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if(l1 == nullptr){
return l2;
}
if(l2 == nullptr){
return l1;
}
if(l1->val <= l2->val){
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else{
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}