Merging two sorted linked lists

前端 未结 14 2179
半阙折子戏
半阙折子戏 2020-12-01 00:12

This is one of the programming questions asked during written test from Microsoft. I am giving the question and the answer that I came up with. Thing is my answer although l

14条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 01:02

    Use recursion. The code is as follows:

    ListNode* mergeTwoSortedLists(ListNode* pHead1, ListNode* pHead2)
    {
        if(pHead1 == NULL)
            return pHead2;
        else if(pHead2 == NULL)
            return pHead1;
    
        ListNode* pMergedHead = NULL;
    
        if(pHead1->m_nValue < pHead2->m_nValue)
        {
            pMergedHead = pHead1;
            pMergedHead->m_pNext = mergeTwoSortedLists(pHead1->m_pNext, pHead2);
        }
        else
        {
            pMergedHead = pHead2;
            pMergedHead->m_pNext = mergeTwoSortedLists(pHead1, pHead2->m_pNext);
        }
    
        return pMergedHead;
    }
    

提交回复
热议问题