Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何打印链接列表的元素?_Python - Fatal编程技术网

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

Python 如何打印链接列表的元素?,python,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 =

今天我要做一个关于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
这就是原始的
\uuuuu init\uuuuuuu
\uuuuu str\uuuuuu
打印列表
,这使得类似于:
1 2 3

我必须将
123code>转换为
[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
调用列表时获得一个内存空间。那么,如何获取非结构化列表呢?

您不应该在节点上调用
str()
,而应该访问它的
cargo

.
.
.    
while node:
    nodelist.append(node.cargo)
    node = node.next
.
.
.

我还建议将
nodelist=[]
作为
printList()
的第一行,然后将
return nodelist
作为最后一行。这使得函数返回一个值,而不是访问全局范围内的变量。
def printLinkedList(self):
    node = self.head
    while node != None:
        print(node.getData())
        node = node.getNext()