Python 如何打印链接列表的元素?
今天我要做一个关于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 =
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()