python 单链表创建,遍历

python 复制代码
# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: [email protected]
@file: 111.py
@time: 2024/05/30 21:37:09
@desc:

"""
# 定义单链表结构
class ListNode:
    def __init__(self,value=0,next=None):
        self.value = value
        self.next = next

    def __str__(self):
        return f"{self.value}->" if self.next else str(self.value)

if __name__ == '__main__':
    # 构建链表
    node = ListNode(0)
    node1 = ListNode(1)
    node2 = ListNode(2)
    node3 = ListNode(3)
    node.next = node1
    node1.next = node2
    node2.next = node3

    # head 指针指向头节点
    head = node
    # 存储遍历结果
    res = ""
    while head:
        res += str(head)
        head = head.next
    print(res)

简化写法:

python 复制代码
# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: [email protected]
@file: 111.py
@time: 2024/05/30 21:37:09
@desc:

"""
# 定义单链表结构
class ListNode:
    """

    """
    def __init__(self,value=0,next=None):
        self.value = value
        self.next = next

    def __str__(self):
        return f"{self.value}->" if self.next else str(self.value)


class SingleListNode:
    """
    单链表
    """
    def __init__(self,lis):
        self.lis = lis
        self.head = ListNode(lis[0])
        self.createListNode()

    def createListNode(self):
        """
        创建
        """
        curr = self.head
        for i in range(1, len(self.lis)):
            new_node = ListNode(self.lis[i])
            curr.next = new_node
            curr = new_node

    def traverseListNode(self):
        """
        遍历
        """
        res = ""
        while self.head:
            res += f"{self.head}"
            self.head = self.head.next
        return res




if __name__ == '__main__':
    lis = [1,2,3,4,5]
    sln = SingleListNode(lis)
    print(sln.traverseListNode())
相关推荐
QQ676580084 分钟前
基于 PyTorch 的 VGG16 深度学习人脸识别检测系统的实现+ui界面
人工智能·pytorch·python·深度学习·ui·人脸识别
木木黄木木5 分钟前
Python制作史莱姆桌面宠物!可爱的
开发语言·python·宠物
exploration-earth29 分钟前
本地优先的状态管理与工具选型策略
开发语言·前端·javascript
胖哥真不错33 分钟前
Python基于方差-协方差方法实现投资组合风险管理的VaR与ES模型项目实战
python·毕业设计·课程设计·方差-协方差方法·投资组合风险管理·var与es模型
慧一居士37 分钟前
flask功能使用总结和完整示例
python
苦学编程的谢1 小时前
Java网络编程API 1
java·开发语言·网络
大模型铲屎官1 小时前
【深度学习-Day 23】框架实战:模型训练与评估核心环节详解 (MNIST实战)
人工智能·pytorch·python·深度学习·大模型·llm·mnist
寒山李白1 小时前
Java 依赖注入、控制反转与面向切面:面试深度解析
java·开发语言·面试·依赖注入·控制反转·面向切面
梓仁沐白1 小时前
【Kotlin】数字&字符串&数组&集合
android·开发语言·kotlin
Java菜鸟、2 小时前
设计模式(代理设计模式)
java·开发语言·设计模式