4 ms in place C code, complexity O(min(m,n))


  • 1
    M
    struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    if (l1 == NULL)  // basic check
        return l2;
    if (l2 == NULL)
        return l1;
        
    struct ListNode *prev, *curr, *post, *head;
    
    if (l1->val < l2->val) {  // head is used to be returned
        head = prev = l1;
        post = l2;
    }
    else {
        head = prev = l2;
        post = l1;
    }
    
    for (curr = prev->next; curr; curr = prev->next)
        if (curr->val > post->val) {    // change the *curr (*post) to be in the other list; 
            prev->next = post;          // loop stops when reach either end of lists
            prev = post;
            post = curr;
            curr = prev->next;
        }
        else
            prev = curr;
    
    if (post)
        prev->next = post;
    
    return head; }

Log in to reply
 

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