我正在使用LinkedLists上的Codewars Kata,并继续收到错误AttributeError:'NoneType'对象没有属性'data'
class Node(object):
def __init__(self, data):
self.data = data
self.next = None`
def push(head, data):
if data == None: return
new_node = Node(data)
new_node.next = head
head = new_node
def build_one_two_three():
head = None
push(head, 3)
push(head, 2)
push(head, 1)
return head
我认为使用if data == None
可以解决问题,但事实并非如此。任何建议都将不胜感激。
答案 0 :(得分:1)
push函数中的行head = new_node
正在替换head指向的本地引用,而不是build_one_two_three函数中head引用的数据。尝试推送返回头,并更新build_one_two_three,其中每次推送更新引用:head = push(head,1)
等。
答案 1 :(得分:0)
我猜您正在寻找以下内容:
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
def push(head, data):
if data == None: return
new_node = Node(data)
new_node.next = head
head = new_node
return head
def build_one_two_three():
head = None
head = push(head, 3)
head = push(head, 2)
head = push(head, 1)
return head
# Just to pretty-print the linked list.
def pp(head):
res = ""
node = head
while node != None:
res += "%s -> " % node.data
node = node.next
res += "None"
print res
if __name__ == "__main__":
head = build_one_two_three()
pp(head)
问题是每次推送新节点时都会覆盖head
的引用。