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()
相关推荐
xlp666hub3 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
明月_清风6 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风6 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
xlp666hub20 小时前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风1 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风1 天前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python
Flittly2 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling2 天前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook2 天前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效