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()
相关推荐
SelectDB40 分钟前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码8 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵19 小时前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li21 小时前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸1 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学1 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab