链接列表属性错误: 'NoneType'对象没有属性'data'



我正在 linkedList 上处理 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可以解决问题,但事实并非如此。任何建议将不胜感激。

push 函数中

head = new_node的行将替换 head 指向的本地引用,而不是 head 在 build_one_two_three 函数中引用的数据。尝试使用推回头,并更新您的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的引用。

相关内容

  • 没有找到相关文章

最新更新