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
相关推荐
carpell几秒前
【语义分割专栏】3:Segnet原理篇
人工智能·python·深度学习·计算机视觉·语义分割
itsuifengerxing几秒前
python 自定义无符号右移
算法
24K纯学渣2 分钟前
Python编码格式化之PEP8编码规范
开发语言·ide·python·pycharm
怒视天下3 分钟前
零基础玩转Python生物信息学:数据分析与算法实现
开发语言·python
zhanshuo22 分钟前
Python元组黑科技:3招让数据安全暴增200%,学生管理系统实战揭秘!
python
空中湖26 分钟前
免费批量图片格式转换工具
图像处理·python·程序人生
猎板PCB厚铜专家大族31 分钟前
高频 PCB 技术发展趋势与应用解析
人工智能·算法·设计规范
dying_man41 分钟前
LeetCode--24.两两交换链表中的结点
算法·leetcode
yours_Gabriel42 分钟前
【力扣】2434.使用机器人打印字典序最小的字符串
算法·leetcode·贪心算法
Mantanmu1 小时前
Python训练day40
人工智能·python·机器学习