C Solution


  • 0
    N
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
        if (NULL == l1) {
            return l2;
        }
        
        if (NULL == l2) {
            return l1;
        }
        
        struct ListNode *head = NULL;
        struct ListNode *tail = NULL;
        struct ListNode *remain = NULL;
        
        while ((NULL != l1) && (NULL != l2)) {
            struct ListNode *tmp = calloc(sizeof(struct ListNode), 1);
            if (l1->val <= l2->val) {
                tmp->val = l1->val;
                l1 = l1->next;
            } else {
                tmp->val = l2->val;
                 l2 = l2->next;
            }
            
            if (NULL == head) {
                head = tail =tmp;
            } else {
                tail->next = tmp;
                tail = tmp;
            }
           
        }
        
        if (NULL == l1) {
            remain = l2;
        } else {
            remain = l1;
        }
        
        while (NULL != remain) {
            struct ListNode *tmp = calloc(sizeof(struct ListNode), 1);
            tmp->val = remain->val;
            tail->next = tmp;
            tail = tmp;
            remain = remain->next;
        }
        
        return head;
    }
    

Log in to reply
 

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