Clean, Easy, Short C++ Solution without recursion


  • 0
    D

    I thinks this will work better than recursive one when dealing a large list.
    Concept is simple: just keep making the list with smaller head be l1.

    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            ListNode *tmp, *head;
            if ( l1 == NULL) return l2;
            if ( l2 == NULL) return l1;
            if ( l1->val > l2->val) {
                tmp = l1;
                l1 = l2;
                l2 = tmp;
            }
            head = l1;
            while (l1->next != NULL){
                if ((l1->next)->val <= l2->val) l1 = l1->next;
                else {
                    tmp = l1->next;
                    l1->next = l2;
                    l1 = l2;
                    l2 = tmp;
                }
            }
            l1->next = l2;
            return head;
        }
    };
    

Log in to reply
 

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