首页 > 代码库 > Merge k Sorted Lists
Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode *merge(ListNode* list1,ListNode* list2)
{
if(list1==NULL && list2==NULL) return NULL;
if(list1==NULL) return list2;
if(list2==NULL) return list1;
ListNode* head;
if(list1->val>list2->val)
{
head=list2;
list2=list2->next;
}
else
{
head=list1;
list1=list1->next;
}
ListNode* p=head;
p->next=NULL;
while(list1!=NULL && list2!=NULL)
{
if(list1->val>list2->val)
{
p->next=list2;
list2=list2->next;
}
else
{
p->next=list1;
list1=list1->next;
}
p=p->next;
p->next=NULL;
}
if(list1!=NULL || list2!=NULL)
{
if(list1==NULL) list1=list2;
while(list1!=NULL)
{
p->next=list1;
list1=list1->next;
p=p->next;
p->next=NULL;
}
}
return head;
}
public:
ListNode *mergeKLists(vector<ListNode *> &lists)
{
int len=lists.size();
if(len==0) return NULL;
if(len==1) return lists[0];
ListNode * head=lists[0];
for(int i=1;i<len;i++)
head=merge(head,lists[i]);
return head;
}
};
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode *merge(ListNode* list1,ListNode* list2)
{
if(list1==NULL && list2==NULL) return NULL;
if(list1==NULL) return list2;
if(list2==NULL) return list1;
ListNode* head;
if(list1->val>list2->val)
{
head=list2;
list2=list2->next;
}
else
{
head=list1;
list1=list1->next;
}
ListNode* p=head;
p->next=NULL;
while(list1!=NULL && list2!=NULL)
{
if(list1->val>list2->val)
{
p->next=list2;
list2=list2->next;
}
else
{
p->next=list1;
list1=list1->next;
}
p=p->next;
p->next=NULL;
}
if(list1!=NULL || list2!=NULL)
{
if(list1==NULL) list1=list2;
while(list1!=NULL)
{
p->next=list1;
list1=list1->next;
p=p->next;
p->next=NULL;
}
}
return head;
}
public:
ListNode *mergeKLists(vector<ListNode *> &lists)
{
int len=lists.size();
if(len==0) return NULL;
if(len==1) return lists[0];
ListNode * head=lists[0];
for(int i=1;i<len;i++)
head=merge(head,lists[i]);
return head;
}
};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。