0
点赞
收藏
分享

微信扫一扫

Merge k Sorted Lists 合并多个链表 归并 vector/copy


Merge k Sorted Lists


Merge k

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
//归并排序 O(NlogK)
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size()==0||lists.empty())
return NULL;
if(lists.size()==1)
return lists[0];

int len=lists.size();
int mid=(len-1)/2;

vector<ListNode *> L,R;
L.resize(mid+1);
R.resize(len-mid-1);
copy(lists.begin(),lists.begin()+mid+1,L.begin());
copy(lists.begin()+mid+1,lists.end(),R.begin());
ListNode *left=mergeKLists(L);
ListNode *right=mergeKLists(R);

return merge(left,right);
}


ListNode *merge(ListNode *a,ListNode *b)
{
if(a==NULL&&b==NULL)
return NULL;
if(a==NULL)
return b;
if(b==NULL)
return a;

ListNode *head=new ListNode(0);
ListNode *ans=head;

while(a && b)
{
if(a->val < b->val)
{
ans->next=a;
a=a->next;
}
else
{
ans->next=b;
b=b->next;
}
ans=ans->next;
}

while(a)
{
ans->next=a;
a=a->next;
ans=ans->next;
}

while(b)
{
ans->next=b;
b=b->next;
ans=ans->next;
}

return head->next;
}
};

举报

相关推荐

0 条评论