leetcode21. 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.

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

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

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

思路:递归

python 复制代码
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if not l1: return l2  # 终止条件,直到两个链表都空
        if not l2: return l1
        if l1.val <= l2.val:  # 递归调用
            l1.next = self.mergeTwoLists(l1.next,l2)
            return l1
        else:
            l2.next = self.mergeTwoLists(l1,l2.next)
            return l2
相关推荐
2601_9679873711 分钟前
Python——入门级(定义功能def函数)
python·函数·可变参数·默认参数·关键字参数
深圳市快瞳科技有限公司1 小时前
野外鸟类AI识别落地实录:输入适配、结构化输出、去重聚合与置信度分流的工程实践
算法·计算机视觉·鸟类识别·鸟类ai识别·野外鸟类观测·林业调查
专注仿真2 小时前
梯度提升类(XFBoost)算法详解与代码实例
开发语言·人工智能·python·算法·大模型训练·控制算法
小豆庄2 小时前
视频遮罩追踪退场后ID撞号的排查—多目标场景下的失效
opencv·算法·bug·视频·python3.11
外收内放3 小时前
Python基础语法练习题(75)
开发语言·python·学习
Tisfy3 小时前
LeetCode 3882.网格图中最小异或路径:动态规划
算法·leetcode·动态规划
黑十4 小时前
PyTorch 报 “no CUDA GPUs are available“ 怎么办?3 步排查
服务器·网络·人工智能·pytorch·python
D e re k ZH4 小时前
P5025 [SNOI2017] 炸弹
c++·算法
A boy CDEF girl4 小时前
算法题专栏:优选算法
数据结构·算法·leetcode
没落之王4 小时前
三易五行看宋朝的三界确立
大数据·人工智能·算法