21. 合并两个有序链表、Leetcode的Python实现

博客主页:🏆 看看是李XX还是李歘歘🏆

🌺每天不定期分享一些包括但不限于计算机基础、算法、后端开发相关的知识点,以及职场小菜鸡的生活。🌺

💗点关注不迷路,总有一些📖知识点📖是你想要的💗
⛽️今天的内容是 Leetcode 203. 移除链表元素 ⛽️💻💻💻

21. 合并两个有序链表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例 1:

输入:l1 = 1,2,4, l2 = 1,3,4

输出:1,1,2,3,4,4

示例 2:

输入:l1 = \[\], l2 = \[\]

输出:\[\]

示例 3:

输入:l1 = \[\], l2 = 0

输出:0

提示:

两个链表的节点数目范围是 0, 50

-100 <= Node.val <= 100

l1 和 l2 均按 非递减顺序 排列

递归:

python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        if list1 is None:
            return list2
        if list2 is None:
            return list1
        if list1.val<list2.val:
            list1.next = self.mergeTwoLists(list1.next,list2)
            return list1
        else:
            list2.next = self.mergeTwoLists(list1,list2.next)
            return list2

迭代:

python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        result = ListNode
        tmp = result
        while list1 is not None and list2 is not None :
            if list1.val<list2.val :
                tmp.next,list1 = list1,list1.next
            else :
                tmp.next,list2 = list2,list2.next
            tmp = tmp.next
        tmp.next = list1 if list1 else list2
        return result.next
相关推荐
梯度下降者11 分钟前
Python - 函数
python·高阶函数·可调用对象·functools·嵌套作用域
starzy19902 小时前
深入理解Scala隐式参数:上下文流转
开发语言·python·scala
wuyk5553 小时前
Spider-第16讲-线程池与竞态问题
大数据·爬虫·python·elasticsearch·搜索引擎
文丑颜不良啊7 小时前
LeetCode3281~3300题目解析
java·leetcode
kyle~9 小时前
FastAPI --- 将业务能力以 API 的形式提供给外部系统
python·fastapi·前后端
aiotto资源分享9 小时前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
梯度下降者10 小时前
Python信号量,条件变量,事件学习
python·条件变量·事件·信号量·线程通信
文丑颜不良啊10 小时前
LeetCode3261~3280题目解析
java·leetcode
MSTcheng.11 小时前
【AI应用实战】用 FastAPI + SSE 做一个自己的 AI 聊天网页:流式输出、多轮对话与完整源码
人工智能·python·大模型·fastapi·sse·ai聊天助手
the局外人12 小时前
Python 实战检索优化:BM25、向量与重排
数据库·后端·python