Accepted basic C++ solution ~ 8ms


  • 1
    D
    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        
            if(l2 == NULL) return l1;
            if(l1 == NULL) return l2;
        
            ListNode* tmp = (l1->val > l2->val) ? l2:l1;
            ListNode* head = tmp;
    
            while(l1!=NULL && l2!=NULL){
     
                if(tmp == l2)
                    l2 = l2->next;
                    
                else 
                    l1 = l1->next;
                    
          
                if(l1 == NULL) {
                    tmp->next = l2;
                    return head;
                }
                
                else if(l2 == NULL){ 
                    tmp->next = l1;
                    return head;
                }
                
                tmp->next = (l1->val > l2->val) ? l2:l1;
                tmp = tmp->next;
                
            }
            
            return head;
        }
    };

Log in to reply
 

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