您的位置:首页 > Web前端

剑指offer----合并两个有序链表

2017-04-17 14:30 531 查看
题目:合并两个递增的有序链表。

注意:测试时一定要考虑全面,当两个链表有一个或两个都为空的情况。

非递归:

ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1==NULL)
return pHead2;
if(pHead2==NULL)
return pHead1;
ListNode* head=NULL;
ListNode* cur=NULL;
if(pHead1->val < pHead2->val)
{

cur=pHead1;
head=cur;
pHead1=pHead1->next;
}
else
{
cur=pHead2;
head=cur;
pHead2=pHead2->next;
}

while(pHead1!=NULL&&pHead2!=NULL)
{
if(pHead1->val < pHead2->val)
{
cur->next=pHead1;
pHead1=pHead1->next;
}
else
{
cur->next=pHead2;
pHead2=pHead2->next;
}
cur=cur->next;

}
if(pHead1!=NULL)
{
cur->next=pHead1;

}
else
{
cur->next=pHead2;

}
return head;
}


递归:

ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1==NULL)
return pHead2;
if(pHead2==NULL)
return pHead1;
if(pHead1->val < pHead2->val)
{

pHead1->next=Merge(pHead1->next,pHead2);
return pHead1;

}
else
{
pHead2->next=Merge(pHead1,pHead2->next);
return pHead2;

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  剑指offer 合并 链表