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
相关推荐
动词ing2 分钟前
【题目练习】算法 组合总和
算法
程序员-Benothing8 分钟前
Linux文本排序统计命令:sort、uniq、wc、cut、tr实战
java·开发语言·算法
开发者联盟league10 分钟前
c++11 使用chrono库转换时间点和字符串,计算时间点间隔
java·c++·算法
溪语流沙18 分钟前
【Web全栈进阶】JWT无状态认证:签发、校验、刷新
前端·git·python·github
reasonsummer22 分钟前
【办公类-112-08】20261009园园通信息合并配学号拆班(数据更新,用年月日期区分版本)
python
阿狗童鞋26 分钟前
Python爬虫进阶实战指南
开发语言·爬虫·python
中原第一高手31 分钟前
fofatoto 1.8.0 发布:启动即知新版本、中文进度面板与更干净的 Web 日志
python·网络安全·开源·资产测绘·fofa
APIshop37 分钟前
淘宝详情接口全解析:从官方开放平台到第三方数据服务
java·python·api
老歌老听老掉牙44 分钟前
两个平面旋转平移坐标系间的坐标变换关系
python·算法·平面·旋转·平移
FITA阿泽要努力44 分钟前
第 1 周·第 3 讲|工具如何交给模型:工具定义、参数与结构化调用
服务器·数据库·python·agent