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
相关推荐
Emma歌小白几秒前
groupby.agg去重后的展平列表通用方法flatten_unique
python
修仙的人1 小时前
【开发环境】 VSCode 快速搭建 Python 项目开发环境
前端·后端·python
幸幸子.1 小时前
LeetCode 组合总数
c++·算法·leetcode
hhhh明1 小时前
Windows11 运行IsaacSim GPU Vulkan崩溃
vscode·python
在钱塘江1 小时前
LangGraph构建Ai智能体-12-高级RAG之自适应RAG
人工智能·python
站大爷IP1 小时前
Python列表基础操作全解析:从创建到灵活应用
python
☆璇1 小时前
【C++】哈希
c++·算法·哈希算法
在钱塘江1 小时前
LangGraph构建Ai智能体-12-高级RAG之纠错式RAG
人工智能·python
朦胧的心一样不平凡1 小时前
robot framework
python