A 12ms C++ Solution


  • 0
    Y
    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            ListNode* l3 = NULL, *curr = NULL;
            while((l1 != NULL)||(l2 != NULL)) {
                if(l3 == NULL) {
                    if((l2 == NULL)||((l1 != NULL)&&(l1->val <= l2->val))) {
                        l3 = l1;
                        curr = l3;
                        l1 = l1->next;
                    } else if((l1 == NULL)||((l2 != NULL)&&(l1->val >= l2->val))) {
                        l3 = l2;
                        curr = l3;
                        l2 = l2->next;
                    }
                }
                
                if((l1 != NULL)&&(l2 != NULL)) {
                    if(l1->val <= l2->val) {
                        curr->next = l1;
                        curr = curr->next;
                        l1 = l1->next;
                    } else {
                        curr->next = l2;
                        curr = curr->next;
                        l2 = l2->next;
                    }
                } else {
                    if((l1 != NULL)||(l2 != NULL)) {
                        if(l1 == NULL) {
                            curr->next = l2;
                            curr = curr->next;
                            l2 = l2->next;
                        } else {
                            curr->next = l1;
                            curr = curr->next;
                            l1 = l1->next;
                        }
                    }
                }
                
            }
            return l3;
        }
    };

Log in to reply
 

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