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
相关推荐
Funny_AI_LAB1 分钟前
AI Agent最新重磅综述:迈向高效智能体,记忆、工具学习和规划综述
人工智能·学习·算法·语言模型·agi
Hui Baby15 分钟前
Java SPI 与 Spring SPI
java·python·spring
执着25917 分钟前
力扣hot100 - 94、二叉树的中序遍历
数据结构·算法·leetcode
-dzk-19 分钟前
【代码随想录】LC 707.设计链表
数据结构·c++·算法·链表
小猪咪piggy20 分钟前
【Python】(3) 函数
开发语言·python
夜鸣笙笙24 分钟前
交换最小值和最大值
python
2301_8223636029 分钟前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
码界奇点40 分钟前
基于Flask与OpenSSL的自签证书管理系统设计与实现
后端·python·flask·毕业设计·飞书·源代码管理
java1234_小锋1 小时前
分享一套优质的基于Python的房屋数据分析预测系统(scikit-learn机器学习+Flask)
python·数据分析·scikit-learn
CCPC不拿奖不改名1 小时前
RAG基础:基于LangChain 的文本分割实战+文本分块
人工智能·python·langchain·知识库·改行学it·rag·向量库