My 8ms and O(n) C++ solution, looking for coding improvement


  • 0
    F
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        //check if either is empty
        if (!l1){return l2;} 
        if (!l2){return l1;}
        
        
        //generate 2 pointers, 'head' always point to the samllest(for final return), 'end' traverse the 2 lists
        ListNode *end, *head;
        if (l1->val<l2->val) {head = l1; l1=l1->next;}
        else {head = l2; l2=l2->next;}
        end = head;
    
        
        while(l1 || l2){
            //if one of the list is Null, append the other one to 'end', then break
            if (!l1){end->next = l2; end=l2; break;}    
            if (!l2){end->next = l1; end=l1; break;}
            
            //if both not empty, append the smaller to 'end', increment the 'end', increment the list
            if(l1->val<l2->val){end->next = l1; end = l1; l1=l1->next;}
            else {end->next = l2; end = l2; l2=l2->next;}
        }
        
        return head;
    }

Log in to reply
 

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