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
相关推荐
光电笑映6 分钟前
STL 源码解密:unordered 系列容器的底层复用与哈希策略
算法·哈希算法·散列表
6Hzlia17 分钟前
【Hot 100 刷题计划】 LeetCode 215. 数组中的第K个最大元素 | C++ 快速选择与堆排序题解
c++·算法·leetcode
小白菜又菜17 分钟前
Leetcode 3070. Count Submatrices with Top-Left Element and Sum Less Than k
算法·leetcode·职场和发展
爱写代码的小朋友22 分钟前
使用 Nuitka 打包 Python 应用:从入门到进阶
开发语言·python
不屈的铝合金23 分钟前
Python入门:数字类型与运算
python·数据类型·python类型判断与转换·python运算符优先级
笨笨饿31 分钟前
32_复变函数在工程中实际应用区别于联系
linux·服务器·c语言·人工智能·单片机·算法·学习方法
智算菩萨37 分钟前
【Python图像处理】3 OpenCV核心操作与图像基本变换
图像处理·python·opencv
会编程的土豆38 分钟前
【数据结构与算法】拓扑排序2
数据结构·算法·leetcode
春蕾夏荷_72829772541 分钟前
pyside2 打包发布exe文件
python
Boop_wu1 小时前
[Java 算法] 栈
java·开发语言·算法