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
相关推荐
xwz小王子3 分钟前
UniBYD:超越人类示教模仿的跨实体机器人操作学习统一框架
学习·算法·机器人·跨实体
W如Q扬8 分钟前
python程序使用supervisor启停
python·supervisor
Piar1231sdafa11 分钟前
蓝莓果实检测与识别——基于decoupled-solo_r50_fpn_1x_coco模型实现
python
拾零吖11 分钟前
Python 常用内置函数
python
跨境卫士苏苏20 分钟前
突围新品广告泥潭:亚马逊广告底层逻辑大重构
大数据·人工智能·算法·重构·亚马逊·防关联
行走的bug...24 分钟前
python项目管理
开发语言·python
其美杰布-富贵-李26 分钟前
tsai 完整训练流程实践指南
python·深度学习·时序学习·fastai
m0_4626052237 分钟前
第N9周:seq2seq翻译实战-Pytorch复现-小白版
人工智能·pytorch·python
纪伊路上盛名在37 分钟前
记1次BioPython Entrez模块Elink的debug
前端·数据库·python·debug·工具开发
CryptoRzz38 分钟前
日本股票 API 对接实战指南(实时行情与 IPO 专题)
java·开发语言·python·区块链·maven