题目:
输入两个递增排序的有序链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的,链表结点的定义如下:
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
简单地用递归实现,主要是注意写出递归出口条件,细心处理。
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (pHead1 == NULL)
return pHead2;
if (pHead2 == NULL)
return pHead1;
ListNode *pMergedList = NULL;
if (pHead1->val <= pHead2->val)
{
pMergedList = pHead1;
pMergedList->next = Merge(pHead1->next,pHead2);
}
else
{
pMergedList = pHead2;
pMergedList->next = Merge(pHead1,pHead2->next);
}
return pMergedList;
}
};