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
相关推荐
luj_17685 小时前
残熵算法实时化三大瓶颈突破
c语言·开发语言·网络·经验分享·算法
充钱大佬6 小时前
Python测试基础教程
python·log4j·apache
mCell6 小时前
你以为短链接只是 Hash + 301/302?
后端·算法·架构
KaMeidebaby7 小时前
卡梅德生物技术快报|抗体亲和力成熟工业化调控新机制:差异性浆细胞增殖工艺优化思路
java·开发语言·人工智能·算法·机器学习·架构·spark
luj_17688 小时前
心形曲线轨迹控制三大关键技术
c语言·开发语言·c++·经验分享·算法
初心丨哈士奇8 小时前
Python 四大基础容器|列表篇
python
tmlx3I0818 小时前
高光谱拼接算法(六)RANSAC 误匹配剔除
人工智能·算法·机器学习
不相心 -w-9 小时前
基础-滑动窗口-(定长 | 不定长)
算法
醉城夜风~9 小时前
Java详解经典算法题:接雨水(三种实现方案+原理剖析)
java·开发语言·算法
明理的信封9 小时前
AI 基础设施的“去 Python 化“:Rust 与 C# 的两条替代路径
人工智能·python·rust