合并两个排序的链表

2021-11-13  本文已影响0人  gaookey

题目:输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

struct ListNode {
    int m_nValue;
    ListNode* m_pNext;
};

ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
    if(pHead1 == nullptr)
        return pHead2;
    else 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;
}

摘抄资料:《剑指offer》

上一篇 下一篇

猜你喜欢

热点阅读