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
相关推荐
love530love1 小时前
Windows 11 下 Z-Image-Turbo 完整部署与 Flash Attention 2.8.3 本地编译复盘
人工智能·windows·python·aigc·flash-attn·z-image·cuda加速
YGGP1 小时前
【Golang】LeetCode 32. 最长有效括号
算法·leetcode
MediaTea1 小时前
Python:模块 __dict__ 详解
开发语言·前端·数据库·python
自然常数e1 小时前
字符函数和字符串函数
c语言·算法·visual studio
jarreyer1 小时前
python,numpy,pandas和matplotlib版本对应关系
python·numpy·pandas
leaves falling2 小时前
c语言分数求和
算法
Das12 小时前
【机器学习】01_模型选择与评估
人工智能·算法·机器学习
代码or搬砖2 小时前
HashMap源码
开发语言·python·哈希算法
星轨初途2 小时前
郑州轻工业大学2025天梯赛解题
c++·经验分享·笔记·算法·链表·剪枝