Detailed C/C++ solution


  • 2
    N
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        //if one of the list is NULL
        if(!l1 || !l2) {
            return l1 != NULL? l1 : l2;
        }
        
       //The head of merged List
        //We need to return this
        ListNode *head;
    
        ListNode *headcur = head;
        ListNode *cur1 = l1;
        ListNode *cur2 = l2;
        
        //Find the first Node
        if(l1->val > l2->val) {
            head = l2;
            cur2 = l2->next;
        } else {
            head = l1;
            cur1 = l1->next;
        }
       
        
        while(cur1 && cur2) {
            //Find the node with smaller val
            //and hook it at the end of the "head" list
            //Move all related cursor to the next node
            if(cur1->val > cur2->val) {
                headcur->next = cur2;
                cur2 = cur2->next;
            } else {
                headcur->next = cur1;
                cur1 = cur1->next;
            }
            headcur = headcur->next;
        }
        
        //Merge the remaining list
        if(cur1) {
            headcur->next = cur1;
        } 
        else if(cur2){
            headcur->next = cur2;
        }
        
        return head;
    }

  • 0

    headcur = l2;
    headcur = l1;
    (in the second if)


  • 0
    C

    why this code is not accept ?


Log in to reply
 

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