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
相关推荐
智购科技智能售货柜8 分钟前
2026自动售货机商品掉落声学计数方案:从麦克风到频谱识别的工程实践~YH
人工智能·算法
CV山月13 分钟前
《DPO 算法详解:不训练奖励模型,如何让大模型直接学会人类偏好?》
人工智能·经验分享·python·大模型·强化学习·研究生
ctlover13 分钟前
网络编程和多线程
开发语言·网络·python
Mr_liu_66617 分钟前
ns3-gym例子解析_基础例子与wifi例子_DQN(3)
开发语言·c++·python·dqn·ns3
weixin_4407305019 分钟前
playwright实战-渠道应用操作
开发语言·前端·python
asdzx6720 分钟前
Python 解析 Excel 数据、图片与图表的实现方案
python·excel
砚底藏山河21 分钟前
存储选型实战:CSV-SQLite-MySQL同机基准(魔码量化实战 #02)
java·数据库·python·金融·maven
土司大王22 分钟前
LeetCode hot100——实现 Trie (前缀树)
java·算法·leetcode
陈年老古董25 分钟前
Python模拟MapReduce分治思想 | 从单文件统计到大文件拆分聚合 学习笔记
开发语言·hadoop·笔记·python·学习
quantdash_cc25 分钟前
数据 API 的稳定性应该如何长期监控?从量化数据监控体系到 QuantDash 实践
开发语言·python·数据分析·量化交易·股票数据·quantdash