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
相关推荐
用户83562907805113 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
Fanxt_Ja13 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下13 小时前
最终的信号类
开发语言·c++·算法
c8i13 小时前
python中类的基本结构、特殊属性于MRO理解
python
茉莉玫瑰花茶13 小时前
算法 --- 字符串
算法
博笙困了14 小时前
AcWing学习——差分
c++·算法
NAGNIP14 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP14 小时前
大模型微调框架之LLaMA Factory
算法
echoarts14 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客14 小时前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法