My 32 lines code in c, only 4 ms. O(n) time


  • 0
    X
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode *cur1 = l1;
        struct ListNode *cur2 = l2;
        struct ListNode *final = malloc(sizeof(struct ListNode));
        struct ListNode *p = final;
        if (l1 == NULL && l2 == NULL) return NULL;
        if (l1 == NULL) return l2;
        if (l2 == NULL) return l1;
        while(cur1 && cur2) {
            struct ListNode *temp;
            if (cur1->val < cur2->val) {
                temp = cur1;
                cur1 = cur1->next;
            } else {
                temp = cur2;
                cur2 = cur2->next;
            }
            p->next = temp;
            p = temp;
        }
        if (cur1) {
            p->next = cur1;
        }
        if (cur2) {
            p->next = cur2;
        }
        p = final->next;
        free(final);
        return p;
    }

Log in to reply
 

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