题目:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
感觉就是上一题的重复版,合并k次即可。
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
if(!l1) return l2;
if(!l2) return l1;
ListNode * head=l1; //把1一直当做新头结点
ListNode * pre=NULL;
while(l1 !=NULL && l2 !=NULL)
{
if( l2->val < l1->val ) //2比1小,就要插到前面
{
ListNode *tmp=l2->next;
l2->next=l1;
if(pre ==NULL) head=l2; //如果1是头结点,更新头
else pre->next=l2; //加入2
pre=l2; //1后移一位
l2=tmp; //2后移一位
}
else
{
pre=l1;
l1=l1->next; //2的点比1的大,直接1右移
}
}
if(l1 ==NULL && l2 !=NULL) //跳出循环说明2后面的都比1大,直接接在后面
pre->next=l2;
return head;
}
ListNode *mergeKLists(vector<ListNode *> &lists)
{
if(lists.size() == 0) return NULL;
ListNode *p = lists[0];
for(int i=1; i<lists.size(); i++){
p = mergeTwoLists(p, lists[i]);
}
return p;
}