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
相关推荐
旷世奇才李先生10 分钟前
PyCharm 安装使用教程
ide·python·pycharm
这里有鱼汤31 分钟前
“对象”?对象你个头!——Python世界观彻底崩塌的一天
后端·python
尘浮72841 分钟前
60天python训练计划----day59
开发语言·python
wh393344 分钟前
使用Python将PDF转换成word、PPT
python·pdf·word
三维重建-光栅投影1 小时前
VS中将cuda项目编译为DLL并调用
算法
船长@Quant1 小时前
数学视频动画引擎Python库 -- Manim Voiceover 语音服务 Speech Services
python·数学·manim·动画引擎·语音旁白
好开心啊没烦恼2 小时前
Python 数据分析:计算,分组统计1,df.groupby()。听故事学知识点怎么这么容易?
开发语言·python·数据挖掘·数据分析·pandas
lljss20203 小时前
Python11中创建虚拟环境、安装 TensorFlow
开发语言·python·tensorflow
课堂剪切板3 小时前
ch03 部分题目思路
算法
空中湖3 小时前
tensorflow武林志第二卷第九章:玄功九转
人工智能·python·tensorflow