A straightforward C++ solution


  • 0
    C
    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
        {
    
            ListNode* current = nullptr;
            ListNode* retPtr = nullptr;
    
            auto iter2 = l2;
            auto iter1 = l1;
    
            while(iter1 or iter2)
            {
                if(iter1 and not iter2)
                {
                    if(not retPtr)
                    {
                        retPtr = iter1;
                    }
                    else
                    {
                        current->next = iter1;
                    }
                    break;
                }
    
                if(iter2 and not iter1)
                {
                    if(not retPtr)
                    {
                        retPtr = iter2;
                    }
                    else
                    {
                        current->next = iter2;
                    }
                    break;
                }
    
                if(iter1->val < iter2->val)
                {
                    if(not retPtr)
                    {
                        current = iter1;
                        retPtr = current;
                    }
                    else
                    {
                        current->next = iter1;
                        current = iter1;
                    }
                    iter1 = iter1->next;
                }
                else
                {
                    if(not retPtr)
                    {
                        current = iter2;
                        retPtr = current;
                    }
                    else
                    {
                        current->next = iter2;
                        current = iter2;
                    }
                    iter2 = iter2->next;
                }
            }
            return retPtr;
        }
    };
    

Log in to reply
 

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