您的位置:首页 > 其它

合并排序的两个链表

2017-03-23 21:54 169 查看
题目:输入两个递增排序的链表,合并这两个链表并使新链表的节点仍然是递增排序的

方法一:递归实现

ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1==nullptr)
return pHead2;
if(pHead2==nullptr)
return pHead1;
ListNode* head=nullptr;
if(pHead1->val < pHead2->val)
{
head=pHead1;
head->next=Merge(pHead1->next, pHead2);
}
else
{
head=pHead2;
head->next=Merge(pHead1, pHead2->next);
}
return head;
}

方法二:非递归实现
Node *ListMerge(Node *head1,Node *head2)
{
if(!head1) return head2;
if(!head2) return head1;
Node *head=NULL;//合并后的头指针
Node *p1=head1;//p1用于扫描链表1
Node *p2=head2;//p2用于扫描链表2
if(head1->value<head2->value)
{
head=head1;
p1=head1->next;
}
else
{
head=head2;
p2=head2->next;
}
Node *p=head;//p永远指向最新合并的结点
while(p1 && p2)//如果循环停止,则p1或p2至少有一个为NULL
{
if(p1->value<p2->value)
{
p->next=p1;
p1=p1->next;
}
else
{
p->next=p2;
p2=p2->next;
}
p=p->next;
}
if(p1)//如果链1还没走完
{
p->next=p1;
}
else if(p2)//如果链2还没走完
{
p->next=p2;
}
return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: