Simple C++ non recursive, no dummy node


  • 0
    N
    class Solution {
    public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode * pResult = nullptr;
        ListNode ** ppLastNext = &pResult;
    
        while (l1 || l2)
        {
            if (l1 == nullptr || (l2 && l2->val <= l1->val))
    	{
                // push from l2, advance l2
    	    *ppLastNext = l2;
    	    l2 = l2->next;
    	}
    	else if (l2 == nullptr || (l1 && l1->val <= l2->val))
    	{
                  // push from l1, advance l1
    	     *ppLastNext = l1;
    	     l1 = l1->next;
    	}
    
    	ppLastNext = &((*ppLastNext)->next)
        }
        return pResult;
    }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.