Solution to the question


  • 0
    V
    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            if( !l1 )
                return l2;
            if( !l2 )
                return l1;
            
            ListNode *head = new ListNode( -1 );
            ListNode *move = head;
        
            while( l1 && l2 )
            {
                if( l1->val < l2->val )
                {
                    move->next = l1;
                    l1 = l1->next;
                }
                else
                {
                    move->next = l2;
                    l2 = l2->next;
                }
                move = move->next;
            }
        
            if( l1 )
                move->next = l1;
            if( l2 )
                move->next = l2;
        
            return head->next;
        }
    };

Log in to reply
 

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