LeetCode21 合并两个有序链表
作者:互联网
LeetCode21 合并两个有序链表
题目
解题
解题一:迭代
// javascript
var mergeTwoLists = function(l1, l2) {
let mergedHead = merged = new ListNode(0);
while (l1 !== null && l2 !== null) {
if (l1.val < l2.val) {
merged.next = l1;
l1 = l1.next;
}
else {
merged.next = l2;
l2 = l2.next;
}
merged = merged.next;
}
// 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
merged.next = (l1 === null) ? l2 : l1;
return mergedHead.next;
};
解题二:递归
// javascript
var mergeTwoLists = function(l1, 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;
}
};
标签:next,链表,解题,l2,有序,l1,null,LeetCode21,merged 来源: https://blog.csdn.net/weixin_45561634/article/details/120629004