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()
相关推荐
睡不醒的kun2 小时前
leetcode算法刷题的第三十二天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
独行soc2 小时前
2025年渗透测试面试题总结-66(题目+回答)
java·网络·python·安全·web安全·adb·渗透测试
Y学院5 小时前
Python 数据分析:从新手到高手的“摸鱼”指南
python·数据分析
深耕AI5 小时前
【PyTorch训练】准确率计算(代码片段拆解)
人工智能·pytorch·python
eqwaak05 小时前
科技信息差(9.12)
开发语言·python·科技·量子计算
Blossom.1186 小时前
从“能写”到“能干活”:大模型工具调用(Function-Calling)的工程化落地指南
数据库·人工智能·python·深度学习·机器学习·计算机视觉·oracle
蒋星熠6 小时前
破壁者指南:内网穿透技术的深度解构与实战方法
网络·数据库·redis·python·websocket·网络协议·udp
shizidushu6 小时前
使用 Pyinstaller 打包 PPOCRLabel
python·pyinstaller
Q_Q19632884757 小时前
python+springboot+uniapp微信小程序题库系统 在线答题 题目分类 错题本管理 学习记录查询系统
spring boot·python·django·uni-app·node.js·php