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
相关推荐
B站_计算机毕业设计之家1 分钟前
豆瓣电影推荐系统 | Python Django Echarts构建个性化影视推荐平台 大数据 毕业设计源码 (建议收藏)✅
大数据·python·机器学习·django·毕业设计·echarts·推荐算法
风暴之零2 分钟前
变点检测算法PELT
算法
深鱼~2 分钟前
视觉算法性能翻倍:ops-cv经典算子的昇腾适配指南
算法·cann
李斯啦果3 分钟前
【PTA】L1-019 谁先倒
数据结构·算法
小镇敲码人7 分钟前
探索华为CANN框架中的ACL仓库
c++·python·华为·acl·cann
KIKIiiiiiiii7 分钟前
微信个人号API二次开发中的解决经验
java·人工智能·python·微信
梵刹古音8 分钟前
【C语言】 指针基础与定义
c语言·开发语言·算法
ZH15455891319 分钟前
Flutter for OpenHarmony Python学习助手实战:Web开发框架应用的实现
python·学习·flutter
Ekehlaft12 分钟前
这款国产 AI,让 Python 小白也能玩转编程
开发语言·人工智能·python·ai·aipy
开源技术16 分钟前
Python GeoPandas基础知识:地图、投影和空间连接
开发语言·ide·python