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;
    }
}
相关推荐
慕容青峰13 小时前
【LeetCode 1925. 统计平方和三元组的数目 题解】
c++·算法·leetcode
冰西瓜60013 小时前
动态规划(一)算法设计与分析 国科大
算法·动态规划
TL滕13 小时前
从0开始学算法——第十一天(字符串基础算法)
笔记·学习·算法
roman_日积跬步-终至千里14 小时前
【计算机算法与设计(10)】习题:苹果买卖问题——分治法的经典应用
算法
deepdata_cn14 小时前
模型预测控制(MPC)算法
算法
独自破碎E14 小时前
如何用最短替换让字符串变平衡?
java·开发语言·算法·leetcode
Jasmine_llq14 小时前
《P1082 [NOIP 2012 提高组] 同余方程》
算法·数学建模·质因数分解(试除法)·快速幂(模幂运算)·欧拉函数计算·基于质因数分解
算家计算14 小时前
AI真的懂你!阿里发布Qwen3-Omni-Flash 全模态大模型:超强交互,人设任选
人工智能·算法·机器学习
l1t14 小时前
利用Duckdb求解Advent of Code 2025第9题 最大矩形面积
数据库·sql·算法·duckdb·advent of code
Swift社区14 小时前
LeetCode 446 - 等差数列划分 II - 子序列
算法·leetcode·职场和发展