问题:输入两个递增排序的链表,合并这两个链表并使新链表的节点仍然是递增排序的。链表节点定义如下:
struct ListNode
{
int m_nValue;
ListNode *m_pNext;
};
解题思路:这很像归并排序。同时要考虑鲁棒性
ListNode *Merge(ListNode *pHead1, ListNode *pHead2)
{
if(pHead1 == nullptr)
return pHead2;
if(pHead2 == nullptr)
return pHead1;
ListNode *pMergedHead = nullptr;
if(pHead1->m_nValue < pHead2->m_nValue)
{
pMergedHead = pHead1;
pMergedHead->m_pNext = Merge(pHead1->m_pNext, pHead2);
}
else
{
pMergedHead = pHead2;
pMergedHead->m_pNext = Merge(pHead1, pHead2->m_pNext);
}
return pMergedHead;
}