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
相关推荐
Forever Nore13 小时前
学完C语言力扣第一题做不来正常吗
数据结构·算法
hansang_IR13 小时前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
今儿敲了吗13 小时前
Python ——第三方包
笔记·python
麒麟水手13 小时前
国产银河麒麟系统开发实录:跑通Streamlit,我踩过的6个坑
python
麒麟水手14 小时前
麒麟系统部署检查清单:上线前30分钟,逐项自查这4类问题
python
Tisfy14 小时前
LeetCode 3731.找出缺失的元素:哈希 / 排序
算法·leetcode·哈希算法·排序·哈希表
用户03321266636715 小时前
使用 Python 在 PDF 中添加或删除数字签名
python
lucas_AI15 小时前
Q-CueGraph:你的多模态大模型会 zoom,但真的知道该看哪儿吗?
人工智能·算法
kaixin_啊啊15 小时前
test_机器学习算法学习
学习·算法·机器学习
liulilittle15 小时前
MOE路由:路由(logits: top-k/8)
c++·人工智能·算法·机器学习·llm