非递归
/**
*
* @param l1 ListNode类
* @param l2 ListNode类
* @return ListNode类
*/
function mergeTwoLists( l1 , l2 ) {
let root = new ListNode(-1);
let now = root;
while (l1 || l2) {
if (!l1 || !l2) {
now.next = l1 ? l1 : l2;
break;
}
if (l1.val > l2.val) {
now.next = l2;
l2 = l2.next;
} else {
now.next = l1;
l1 = l1.next;
}
now = now.next;
}
return root.next;
} 递归
/**
*
* @param l1 ListNode类
* @param l2 ListNode类
* @return ListNode类
*/
function mergeTwoLists( l1 , l2 ) {
if (!l1 || !l2) return l1 ? l1 : l2;
let res = null;
if (l1.val > l2.val) {
res = l2;
res.next = mergeTwoLists(l1, l2.next);
} else {
res = l1;
res.next = mergeTwoLists(l1.next, l2);
}
return res;
} 递归精简版
function mergeTwoLists( l1 , l2 ) {
if (!l1 || !l2) return l1 ? l1 : l2;
return l1.val > l2.val ?
((l2.next = mergeTwoLists(l1, l2.next)) ? l2 : l2) :
((l1.next = mergeTwoLists(l1.next, l2)) ? l1 : l1);
} 
京公网安备 11010502036488号