剑指offer----合并两个有序链表
2017-04-17 14:30
531 查看
题目:合并两个递增的有序链表。
注意:测试时一定要考虑全面,当两个链表有一个或两个都为空的情况。
非递归:
递归:
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;
}
}
}
注意:测试时一定要考虑全面,当两个链表有一个或两个都为空的情况。
非递归:
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】合并两个有序的链表
- 3.剑指offer-合并两个有序的链表
- 剑指offer--递归非递归合并两个有序链表
- 剑指offer面试题-合并两个有序链表
- 剑指OFFER——合并两个有序的链表
- 剑指Offer---面试题17:合并两个有序链表
- 【剑指offer】合并两个有序的链表
- 剑指Offer之合并两个有序的链表
- 剑指Offer_面试题17_合并两个有序链表
- 剑指offer 合并两个有序链表
- 【剑指offer】链表相关-合并两个有序链表&递归写法17
- 【面试题】剑指Offer-17-合并两个有序的单链表
- 【剑指offer】第二十四题(反转链表) 和 第二十五题(合并两个有序链表)
- [九度OnlineJudge][剑指Offer]题目1519:合并两个排序的链表
- 【newCoder】剑指Offer_编程题 合并两个排序的链表
- 【剑指Offer面试编程题】题目1519:合并两个排序的链表--九度OJ
- 【剑指offer】面试题25:合并两个排序的链表
- 【剑指offer】面试题 25:合并两个排序的链表
- 剑指Offer面试题25:合并两个排序的链表
- 剑指offer--合并两个排序的链表