# My recursive way to solve this problem(JAVA, easy understanding)

• Hello every one, here is my code, simple but works well:

``````public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}

if(l1.val < l2.val){
}
else{
}
}
}``````

• Wow! Marvelous! Every time you find the smaller one as the merge head meanwhile it's the last recursive procession's next node. Easy to understand and easy to code.

• Thanks!!!!!!!!!!!!!!!!!!

• nice solution!

(potentially stack overflow)

• @zwangbo Very nice solution. Thanks for sharing it

• It will occur stack overflow if list length is too long.

• Thanks, your code is very to understand!

• However the recursive solution would modify the input parameters! This is not good, and I've no idea whether it's bad~

• cool！thanks！

• Hi, I make a small change for your code.
It is much more simple.

``````public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) return l2;
if(l2 == null) return l1;

if(l1.val < l2.val){
l1.next = mergeTwoLists(l1.next, l2);
return l1;
}
else{
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}
``````

• This post is deleted!

• @zwangbo What is the time complexity of this algorithm ?
Is it O(n+m) ? length of first list and length of second list