I was trying do the merge in recursive way, but the result shows: memory limit exceeded..


  • 0
    L

    Is the question needed us consider the stack memory?

    if(l1 == null){
    return l2;
    }

        if(l2 == null){
            return l1;
        }
        
        ListNode smallNode = (l1.val <= l2.val) ? l1 : l2;
        ListNode bigNode = (l1.val >= l2.val) ? l1 : l2;
        
        smallNode.next = mergeTwoLists(smallNode.next, bigNode);
        
        return smallNode;

  • 1
    R

    Beautiful solution! It has just one extra character though.

    ListNode bigNode = (l1.val >= l2.val) ? l1 : l2;
    

    Just make the above comparison '>' instead of '>='. Your program runs successfully.

    Because of your previous logic, smallNode and bigNode refers to the same node if their values are equal and it will result in an infinite loop.


  • 0
    L

    I tried, but still that error


  • 0
    R

    It works. The solution is accepted when I submitted it. I am posting it again here.

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l1 == null) return l2;
            if(l2 == null) return l1;
            ListNode smallNode = (l1.val <= l2.val) ? l1 : l2;
            ListNode bigNode = (l1.val > l2.val) ? l1 : l2;
            smallNode.next = mergeTwoLists(smallNode.next, bigNode);
            return smallNode;
        }

Log in to reply
 

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