如何打印链接列表的元素?

2024-09-20 23:00:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我今天要做一个关于python的节点练习。我似乎完成了其中的一部分,但并不是完全成功。

class Node:
    def __init__(self, cargo=None, next=None):
        self.cargo = cargo
        self.next  = next

    def __str__(self):
        return str(self.cargo)

node1 = Node(1)
node2 = Node(2)
node3 = Node(3)

node1.next = node2
node2.next = node3

def printList(node):
  while node:
    print node,
    node = node.next
  print

所以这就是原始的__init____str__printList,这使得类似于:1 2 3

我必须把1 2 3转换成[1,2,3]

我在创建的列表中使用了append

nodelist = []

node1.next = node2
node2.next = node3


def printList(node):
    while node:
        nodelist.append(str(node)), 
        node = node.next

但我名单上的东西都是一串,我不想那样。

如果我消除了str转换,那么当我用print调用列表时,只会得到一个内存空间。那我怎么才能得到一个无张力的列表呢?


Tags: selfnonenode列表initdefnextprint

热门问题