python 单链表创建,遍历

python 复制代码
# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: JHC000abc@gmail.com
@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: JHC000abc@gmail.com
@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())
相关推荐
百锦再3 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
m0_736919104 小时前
C++代码风格检查工具
开发语言·c++·算法
喵手5 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控
2501_944934735 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
helloworldandy5 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
黎雁·泠崖5 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
2301_763472466 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
肖永威6 小时前
macOS环境安装/卸载python实践笔记
笔记·python·macos
TechWJ7 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
枷锁—sha7 小时前
【SRC】SQL注入WAF 绕过应对策略(二)
网络·数据库·python·sql·安全·网络安全