LeetCode 21. 合并两个有序链表

21. Merge Two Sorted Lists

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Example 1:

Input: list1 = 1,2,4, list2 = 1,3,4

Output:1,1,2,3,4,4

Example 2:

Input: list1 = \[\], list2 = \[\]

Output: \[\]

Example 3:

**Input:**list1 = \[\], list2 = 0

Output:0

Constraints:

  • The number of nodes in both lists is in the range 0, 50.
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.

解法思路:

1、递归

2、迭代

法一:

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        // Recursion
        // Time: O(m+n)
        // Space: O(m+n)
        if (list1 == null) {
            return list2;
        } else if (list2 == null) {
            return list1;
        } else if (list1.val < list2.val){
            list1.next = mergeTwoLists(list1.next, list2);
            return list1;
        } else {
            list2.next = mergeTwoLists(list1, list2.next);
            return list2;
        }
    }
}

法二:

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        // Iterator double pointer
        // Time: O(m+n)
        // Space: O(1)
        ListNode dummyNode = new ListNode(0);
        ListNode cur = dummyNode;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                cur.next = list1;
                list1 = list1.next;
            } else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        cur.next = list1 != null ? list1 : list2;
        return dummyNode.next;
    }
}
相关推荐
_清歌6 小时前
DSpark 深度解读:DeepSeek-V4 如何用「半自回归」把推理速度提升 85%
算法
统计实现局6 小时前
SVD 的三步走:双对角化、Givens 收敛、排序
算法
躬行见万象6 小时前
《VLA 系列》UniLab 强化训练 | G1 机器人 |复现
算法
统计实现局6 小时前
对称不定分解(Bunch-Kaufman):为什么 Cholesky 不够用
算法
统计实现局6 小时前
dqrsl 拆解:拿着 QR 结果能算出哪 5 种东西
算法
统计实现局7 小时前
为什么 Cholesky 求逆比 Gauss-Jordan 快一倍——行列式溢出防护详
算法
To_OC18 小时前
LC 994 腐烂的橘子:人人都说是 BFS 入门题,我却写了三遍才过
javascript·算法·leetcode
金銀銅鐵21 小时前
[Python] 扩展欧几里得算法
python·数学·算法
To_OC1 天前
LC 200 岛屿数量:经典 DFS 入门题,我第一次写居然连方向都搞错了
javascript·算法·leetcode