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
相关推荐
Kuo-Teng3 分钟前
LeetCode 206: Reverse Linked List
java·算法·leetcode·职场和发展
檀越剑指大厂4 分钟前
【Python系列】fastapi和flask中的阻塞问题
python·flask·fastapi
庸子1 小时前
Kubernetes调度器深度解析:从资源分配到亲和性策略的架构师之路
java·算法·云原生·贪心算法·kubernetes·devops
YoungHong19921 小时前
【Python进阶】告别繁琐Debug!Loguru一键输出异常日志与变量值
python·debug·异常处理·日志·loguru·log·logger
Sunhen_Qiletian1 小时前
YOLOv2算法详解(上篇):从经典到进化的目标检测之路
算法·yolo·目标检测
QTreeY1231 小时前
detr目标检测+deepsort/strongsort/bytetrack/botsort算法的多目标跟踪实现
人工智能·算法·yolo·目标检测·计算机视觉·目标跟踪
AiXed2 小时前
PC微信协议之nid算法
python·网络协议·算法·微信
小李哥哥2 小时前
基于数据的人工智能建模流程及源码示例
python
谈笑也风生2 小时前
经典算法题之子集(四)
算法
mit6.8243 小时前
划分dp+滑窗+前缀和|deque优化
算法