🔗 LeetCode 21 - Merge Two Sorted Lists
📌 题目描述
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
1 2
| 输入: l1 = [1,2,4], l2 = [1,3,4] 输出: [1,1,2,3,4,4]
|
💡 解题思路
使用 递归 或 迭代 方法逐步将两个链表中较小的节点连接起来;
递归写法简洁优雅,但迭代写法更容易控制空间复杂度。
时间复杂度:O(n + m),其中 n 和 m 分别是两个链表的长度;
空间复杂度:
- 递归:O(n + m),因为递归栈;
- 迭代:O(1)
✅ JavaScript 实现(迭代)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| var mergeTwoLists = function(l1, l2) { let dummy = new ListNode(-1); let current = dummy;
while (l1 !== null && l2 !== null) { if (l1.val <= l2.val) { current.next = l1; l1 = l1.next; } else { current.next = l2; l2 = l2.next; } current = current.next; }
current.next = l1 !== null ? l1 : l2;
return dummy.next; };
|
✅ JavaScript 实现(递归)
1 2 3 4 5 6 7 8 9 10 11 12
| 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; } };
|
🧠 思考拓展
- 如何在不创建新链表节点的情况下合并?
- 如果链表不是升序而是无序,如何合并后排序?