python LeetCode 刷题记录 21

题目

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

注意:是链表

代码

bash 复制代码
class Solution:
    def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        if l1 and l2:
            if l1.val > l2.val: 
                l1, l2 = l2, l1
            l1.next = self.mergeTwoLists(l1.next, l2)
        return l1 or l2

使用递归,比较头节点,将小的头节点指向取出,将剩下的两个链表继续传入函数,将小的头节点指向函数返回的链表。

链表基本操作

bash 复制代码
class LinkNode():
    def __init__(self, val = 0, next=None):
        self.val = val
        self.next = next

    def __str__(self):
        # 必须返回字符串对象
        return str(self.val) + '-->' if self.next else str(self.val)


class LinkList():
    def creat_link_list(self):
        self.head = None
        node1 = LinkNode(1)
        node2 = LinkNode(0)
        node3 = LinkNode(1)
        print('node1:', node1)
        node1.next = node2
        node2.next = node3
        self.head = node1


    def show_link_list(self):
        current = self.head
        result = ""
        while current:
            result += str(current)
            current = current.next
        print(result)


if __name__ == '__main__':
    linklist = LinkList()
    linklist.creat_link_list()
    linklist.show_link_list()
相关推荐
alvin_20058 分钟前
python之OpenGL应用(五)变换
python·opengl
深蓝电商API16 分钟前
服务器部署爬虫:Supervisor 进程守护
爬虫·python
是梦终空11621 分钟前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python
竹林81834 分钟前
用Python requests搞定Cookie登录,我绕过了三个大坑才成功
爬虫·python·自动化运维
Frostnova丶1 小时前
LeetCode 3296. 使山区高度为零的最少秒数
算法·leetcode
MIXLLRED1 小时前
Python模块详解(一)—— socket 和 threading 模块
开发语言·python·socket·threading
Jay-r1 小时前
OpenClaw养龙虾工具安全风险分析:五大隐患及防护建议引言
网络·python·安全·web安全·ai助手·openclaw
样例过了就是过了1 小时前
LeetCode热题100 全排列
数据结构·c++·算法·leetcode·dfs
程序员夏末1 小时前
【LeetCode | 第六篇】算法笔记
笔记·算法·leetcode
C蔡博士2 小时前
最近点对问题(Closest Pair of Points)
java·python·算法