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
相关推荐
珺毅同学2 小时前
YOLO生成预测json标签迁移问题
python·yolo·json
骑士雄师2 小时前
18.4 长期记忆可修改版
python
~小先生~2 小时前
Python从入门到放弃(一)
开发语言·python
天佑木枫2 小时前
第2天:变量与数据类型 —— 让程序记住信息
python
小宋加油啊3 小时前
机械臂抓取物体 PVN3D算法调研学习
学习·算法·3d
lqqjuly3 小时前
前沿算法深度解析(一)
算法
Dust-Chasing3 小时前
Claude Code源码剖析 - Claude Code 上下文压缩机制
人工智能·python·ai
小欣加油4 小时前
leetcode1926 迷宫中离入口最近的出口
数据结构·c++·算法·leetcode·职场和发展
Cloud_Shy6184 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 33 - 35)
开发语言·人工智能·笔记·python·学习方法