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
相关推荐
教练、我想打篮球1 分钟前
12 pyflink 的一个基础使用, 以及环境相关
python·flink·pyflink
RTC老炮7 分钟前
webrtc弱网-RembThrottler类源码分析及算法原理
网络·算法·webrtc
飞翔的佩奇11 分钟前
【完整源码+数据集+部署教程】【天线&运输】直升机战机类型识别目标检测系统源码&数据集全套:改进yolo11-CSP-EDLAN
前端·python·yolo·计算机视觉·数据集·yolo11·直升机战机类型识别目标检测系统
C嘎嘎嵌入式开发12 分钟前
(21)100天python从入门到拿捏《XML 数据解析》
xml·开发语言·python
蓝博AI21 分钟前
基于卷积神经网络的香蕉成熟度识别系统,resnet50,vgg16,resnet34【pytorch框架,python代码】
人工智能·pytorch·python·神经网络·cnn
野蛮人6号31 分钟前
力扣热题100道之73矩阵置零
算法·leetcode·矩阵
野蛮人6号33 分钟前
力扣热题100道之238除自身以外数组的乘积
算法·leetcode·职场和发展
坚持编程的菜鸟37 分钟前
LeetCode每日一题——缀点成线
c语言·算法·leetcode
小白银子42 分钟前
零基础从头教学Linux(Day 54)
linux·windows·python
派大星爱吃猫1 小时前
直接插入排序详解
算法·排序算法·直接插入排序