Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
题意
合并k个排好序的链表,并返回这个排好序的链表。
题解
两个两个合并,即复用[leetcode] 【排序】 21. Merge Two Sorted Lists这题的函数。
/**
* 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;
ListNode* cur=lists[0];
for(int i=1;i<lists.size();i++)
cur=mergeTwoLists(cur,lists[i]);
return cur;
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(!l1) return l2;
if(!l2) return l1;
ListNode newstart(-1);
ListNode* p=&newstart;
for(;l1!=NULL&&l2!=NULL;p=p->next)
{
if(l1->val<l2->val)
{
p->next=l1;
l1=l1->next;
}
else
{
p->next=l2;
l2=l2->next;
}
}
p->next=l1!=NULL ? l1 :l2;
return newstart.next;
}
};