C++ simple iterative and recursive solutions


  • 3
    Z
    class Solution {
    public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        //return solution1(l1, l2);       //iterative
        //return solution2(l1, l2);       //recursive
        return solution3(l1, l2);       //recursive
    }
    private:
    ListNode *solution1(ListNode *l1, ListNode *l2){
        if(!l1 && !l2) return NULL;
        if(!l1 || !l2) return !l1 ? l2 : l1;
        ListNode *newHead, *cur;
        newHead = l1->val > l2->val ? l2 : l1;
        cur = newHead;
        l1->val > l2->val ? l2=l2->next : l1=l1->next;
        while(l1 && l2){
            cur->next = l1->val > l2->val ? l2 : l1;
            l1->val > l2->val ? l2=l2->next : l1=l1->next;
            cur = cur->next;
        }
        cur->next = l1 == NULL ? l2 : l1;
        return newHead;
    }
    ListNode *solution2(ListNode *l1, ListNode *l2){
        if(!l1 && !l2) return NULL;
        if(!l1 || !l2) return !l1 ? l2 : l1;
        ListNode *node;
        if(l1->val < l2->val){
            node = l1;
            node->next = solution2(l1->next, l2);
        }else{
            node = l2;
            node->next = solution2(l1, l2->next);
        }
        return node;
    }
    ListNode *solution3(ListNode *l1, ListNode *l2){
        if(!l1 && !l2) return NULL;
        if(!l1 || !l2) return !l1 ? l2 : l1;
        ListNode *node = l1->val < l2->val ? l1 : l2;
        node->next = solution3(l1->val < l2->val ? l1->next : l1, l1->val < l2->val ? l2 : l2->next);
        return node;
    }
    };

Log in to reply
 

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