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())
相关推荐
乌鸦94417 分钟前
《类和对象(下)》
开发语言·c++·类和对象+
炒空心菜菜28 分钟前
SparkSQL 连接 MySQL 并添加新数据:实战指南
大数据·开发语言·数据库·后端·mysql·spark
张小九9934 分钟前
PyTorch的dataloader制作自定义数据集
人工智能·pytorch·python
zstar-_44 分钟前
FreeTex v0.2.0:功能升级/支持Mac
人工智能·python·macos·llm
苏生要努力1 小时前
第九届御网杯网络安全大赛初赛WP
linux·python·网络安全
多多*1 小时前
算法竞赛相关 Java 二分模版
java·开发语言·数据结构·数据库·sql·算法·oracle
前进的程序员1 小时前
嵌入式开发中 C++ 跨平台开发经验与解决方案
开发语言·c++
于壮士hoho1 小时前
DeepSeek | AI需求分析
人工智能·python·ai·需求分析·dash
蒙奇D索大1 小时前
【人工智能】自然语言编程革命:腾讯云CodeBuddy实战5步搭建客户管理系统,效率飙升90%
人工智能·python·django·云计算·腾讯云
乌夷1 小时前
axios结合AbortController取消文件上传
开发语言·前端·javascript