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()
相关推荐
爱昏羔20 小时前
下篇:从检索到交互 — 物流RAG问答系统与WebUI全实现
python·langchain·agent
_Jimmy_20 小时前
Agent引用数据库知识过时的增量同步方案
人工智能·python·langchain
min(a,b)1 天前
学习第 4 天:面向对象与异常处理
python·学习·学习方法
yangshicong1 天前
第19章:AI安全防护与AI安全
人工智能·python·安全·prompt·ai编程
果汁华1 天前
Function Calling 与 Python 实战完整指南
开发语言·网络·python
c_lb72881 天前
2026年不同基础做量化,先找AI能参与的位置
人工智能·python
chenment1 天前
ComfyUI 自定义节点开发:从零扩展你的图像生成工作流
python·stable diffusion
IT空门:门主1 天前
Python 基础语法学习路线图
网络·python·学习
yyds_yyd_100861 天前
1464. 数组中两元素的最大乘积(2026.07.27)
数据结构·c++·算法·leetcode
互联网中的一颗神经元1 天前
小白python入门 - 25. SQL 与表设计入门
数据库·python·sql