LinkedList AttributeError: 'NoneType' object has no attribute 'data'

LinkedList AttributeError: 'NoneType' object has no attribute 'data'

我正在处理 linkedLists 上的 Codewars Kata,并不断收到错误 AttributeError: 'NoneType' object has no attribute '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 可以解决问题,但事实并非如此。任何建议将不胜感激。

推送函数中的 head = new_node 行正在替换 head 指向的本地引用,而不是 head 在 build_one_two_three 函数中引用的数据。尝试推送 return head,并更新你的 build_one_two_three,每次推送都会更新引用:head = push(head,1),等等

我猜您正在寻找以下内容:

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 的引用。