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())
相关推荐
VBA6337几秒前
VBA数据库解决方案第十五讲:Recordset集合中单个数据的精确处理
开发语言
wrx繁星点点4 分钟前
事务的四大特性(ACID)
java·开发语言·数据库
不写八个10 分钟前
Python办公自动化教程(005):Word添加段落
开发语言·python·word
HEX9CF15 分钟前
【CTF Web】Pikachu xss之href输出 Writeup(GET请求+反射型XSS+javascript:伪协议绕过)
开发语言·前端·javascript·安全·网络安全·ecmascript·xss
_.Switch28 分钟前
Python机器学习框架介绍和入门案例:Scikit-learn、TensorFlow与Keras、PyTorch
python·机器学习·架构·tensorflow·keras·scikit-learn
赵荏苒40 分钟前
Python小白之Pandas1
开发语言·python
丶Darling.42 分钟前
代码随想录 | Day26 | 二叉树:二叉搜索树中的插入操作&&删除二叉搜索树中的节点&&修剪二叉搜索树
开发语言·数据结构·c++·笔记·学习·算法
人生の三重奏1 小时前
前端——js补充
开发语言·前端·javascript
平凡的小码农1 小时前
JAVA实现大写金额转小写金额
java·开发语言
一眼万里*e1 小时前
fish-speech语音大模型本地部署
python·flask·大模型