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;
    }
}
相关推荐
明月看潮生1 小时前
青少年编程与数学 02-018 C++数据结构与算法 06课题、树
数据结构·c++·算法·青少年编程·编程与数学
小指纹1 小时前
动态规划(一)【背包】
c++·算法·动态规划
_安晓1 小时前
数据结构 -- 图的应用(一)
数据结构·算法·图论
阳洞洞1 小时前
leetcode 二分查找应用
算法·leetcode·二分查找
猎猎长风1 小时前
【数据结构和算法】1. 数据结构和算法简介、二分搜索
数据结构·算法
Pasregret1 小时前
模板方法模式:定义算法骨架的设计模式
算法·设计模式·模板方法模式
左灯右行的爱情2 小时前
JVM-卡表
java·jvm·算法
hy.z_7773 小时前
【数据结构】线性表( List)和 顺序表(ArrayList)
数据结构·list
奋斗者1号3 小时前
逻辑回归:使用 S 型函数进行概率预测
算法·机器学习·逻辑回归
CodeJourney.3 小时前
基于DeepSeek与Excel的动态图表构建:技术融合与实践应用
数据库·人工智能·算法·excel