gpt4 book ai didi

python - 打印链表节点

转载 作者:行者123 更新时间:2023-12-01 08:06:04 24 4
gpt4 key购买 nike

我想首先创建链接列表,然后打印列表列表节点。我尝试了几种方法,但总是得到错误的输出。

下面是我的代码:

class node:
def __init__(self, dataVal=None):
self.dataVal = dataVal
self.nextVal = None

class LinkedList:
def __init__(self):
self.headVal = None

def printList(self):
printVal = self.headVal
while printVal is not None:
print(printVal.dataVal)
printVal = printVal.nextVal

def insertEnd(self, n_node):
new_node = node(n_node)
if self.headVal is None:
self.headVal = node(new_node)
else:
end = self.headVal
while(end.nextVal):
end = end.nextVal
end.nextVal = new_node

def createList(array, n):
linkedList = LinkedList()
for i in range(n):
linkedList.insertEnd(array[i])
return linkedList

if __name__=='__main__':
t = 2
n = [5,6]
array = [[1,2,3,4,5], [2,3,6,7,5,1]]
for i in range(t):
head = createList(array[i], n[i])
print(head.printList())

我当前的输出:

<__main__.node object at 0x0000026152300400>
2
3
4
5
None
<__main__.node object at 0x00000261523257B8>
3
6
7
5
1
None

我的预期应该是:

<__main__.node object at 0x0000026152300400>
1
2
3
4
5

<__main__.node object at 0x00000261523257B8>
2
3
6
7
5
1

我不知道为什么会出现“None”,也不知道为什么也会打印该对象。有人可以帮忙吗?

最佳答案

删除打印以摆脱None。改变

print(head.printList())

head.printList()

还有

if self.headVal is None:

相当于但更Pythonic

if not self.headVal:

关于python - 打印链表节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55527092/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com