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

• 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;``````

• 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.

• I tried, but still that error

• 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;
}``````

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