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()
相关推荐
sunshineine5 分钟前
FreeCAD
python
dinl_vin14 分钟前
Python 并发编程实战:多线程、协程与多进程全解析
开发语言·人工智能·python
长空任鸟飞_阿康29 分钟前
驾驭 AI 这匹野马:深入解析智能体 Harness 工程
人工智能·python·ai
skywalk816344 分钟前
请结合以下说明,先完成类似python的内置函数。 然后再去完成内置库(标准款) ‌内置函数‌
开发语言·python
郝学胜-神的一滴1 小时前
Python 高级编程 018:深挖 super
开发语言·python·程序人生·软件构建
2401_868534781 小时前
2026年5月系统分析
数据结构·python·tornado
专注VB编程开发20年1 小时前
python翻译网页HTML的难题
python·c#·html
new【一个】对象1 小时前
登录与注册完整流程分析
python
仙俊红2 小时前
线程池面试
python·面试·职场和发展
SilentSamsara2 小时前
爬虫工程化:Playwright + 反反爬 + 数据清洗管道实战
开发语言·爬虫·python·青少年编程·playwright