public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode ans = new ListNode(0);
ListNode prev = ans;
while(l1 != null && l2 != null){
if(l1.val > l2.val){
prev.next = l2;
l2 = l2.next;
} else{
prev.next = l1;
l1 = l1.next;
}
prev = prev.next;
}
if(l2 == null){
prev.next = l1;
} else {
prev.next = l2;
}
return ans.next;
}
JAVA Easy to understand solution


Thanks a lot for your iteration version!
Based on your solution, I made the following implementation, which is more lengthy than yours, but maybe easier to understand for some people. Thank you again!public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; ListNode head = null; if (l1.val >= l2.val) { head = l2; l2 = l2.next; } else // l1.val < l2.val { head = l1; l1 = l1.next; } ListNode curNode = head; while (l1 != null && l2 != null) { if (l1.val >= l2.val) { curNode.next = l2; l2 = l2.next; } else // l1.val < l2.val { curNode.next = l1; l1 = l1.next; } curNode = curNode.next; } if (l1 == null) curNode.next = l2; else if (l2 == null) curNode.next = l1; return head; }