这些是我的代码
class Node():
'''A node in a linked list'''
def __init__(self, data, next_node=None):
self.data = data
self.next_node = next_node
def sum(LL):
head = LL
# If Linked list is empty, return 0
if (head.data is None or head.data == []):
result = 0
# If Linked List contain only 1 node then return it
elif (head.next_node is None):
result = head.data
else:
curr = head
result = curr.data
# If next is not None then add up to result
while (curr.next_node is not None):
curr = curr.next_node
result += curr.data
return result
问题在代码的末尾
while (curr.next_node is not None):
curr = curr.next_node
result += curr.data
如果我尝试这个
LL = Node(1, Node(2, 3))
sum(LL)
我不明白为什么它说
hindins.attributeerror:'int'对象没有属性'data'
while循环工作直到达到最后一个节点
结果应为6
,因为 3
是您的下一个节点。您可能想要:
LL = Node(1, Node(2, Node(3)))
您指向一个不存在的节点。第二个嵌套节点指向下一个节点3,但是该节点不存在母猪,它去寻找其数据,找不到任何地方。
如何呢?通过链接列表创建迭代器以迭代。然后,您有一个标准迭代器,只需用内置的总和函数总结:
def traverse(LL):
head = LL
while (head):
yield head.data
head = head.next_node
sum(traverse(LL))