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
相关推荐
2501_9418053118 分钟前
智慧零售平台中的多语言语法引擎与实时推荐系统实践
leetcode
u***32433 小时前
使用python进行PostgreSQL 数据库连接
数据库·python·postgresql
青瓷程序设计6 小时前
动物识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
tobebetter95276 小时前
How to manage python versions on windows
开发语言·windows·python
F_D_Z6 小时前
数据集相关类代码回顾理解 | sns.distplot\%matplotlib inline\sns.scatterplot
python·深度学习·matplotlib
daidaidaiyu7 小时前
一文入门 LangGraph 开发
python·ai
CoderYanger7 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
夏鹏今天学习了吗7 小时前
【LeetCode热题100(72/100)】前 K 个高频元素
leetcode
不知更鸟8 小时前
前端报错:快速解决Django接口404问题
前端·python·django
4***72138 小时前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django