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
相关推荐
AI Echoes5 分钟前
别再手工缝合API了!开源LLMOps神器LMForge,让你像搭积木一样玩转AI智能体!
人工智能·python·langchain·开源·agent
AI Echoes8 分钟前
从零构建企业级LLMOps平台:LMForge——支持多模型、可视化编排、知识库与安全审核的全栈解决方案
人工智能·python·langchain·开源·agent
源代码•宸19 分钟前
Leetcode—2749. 得到整数零需要执行的最少操作数【中等】(__builtin_popcountl)
c++·经验分享·算法·leetcode·位运算
用户48221371677520 分钟前
深度学习——AlexNet网络结构
算法
beijingliushao1 小时前
58-正则表达式
数据库·python·mysql·正则表达式
陈敬雷-充电了么-CEO兼CTO1 小时前
具身智能多模态感知与场景理解:融合语言模型的多模态大模型
人工智能·python·gpt·语言模型·自然语言处理·chatgpt·多模态
荔枝吻1 小时前
【AI总结】Python BERT 向量化入门指南
人工智能·python·bert
张子夜 iiii1 小时前
传统神经网络实现-----手写数字识别(MNIST)项目
人工智能·pytorch·python·深度学习·算法
Rhys..1 小时前
python + Flask模块学习 1 基础用法
python·学习·前端框架·flask
飞翔的佩奇1 小时前
【完整源码+数据集+部署教程】骰子点数识别图像实例分割系统源码和数据集:改进yolo11-DCNV2
python·yolo·计算机视觉·数据集·yolo11·骰子点数识别图像实例分割