AttributeError:“ NoneType”对象没有属性“ next”

时间:2019-12-27 16:30:04

标签: python

我是Python的新手,我正在做Leetcode Problem,却无法理解为什么我得到属性错误“ NoneType”对象没有属性“ next”(deleteDuplicates中的第24行)。正确地为两个noDuplicatesList / Itr分配了一个值,因此它们的属性“ next”应该起作用...

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if (head is None):
            return head

        # first element has a non-null value
        # noDuplicatesList points to list head
        # noDuplicatesItr traces list items
        noDuplicatesList = ListNode(head.val)
        noDuplicatesItr = noDuplicatesList

        # iterate down original list
        while (head.next.val != None):
            if (head.val != head.next.val):
                noDuplicatesItr.next = ListNode(head.next.val)
            head = head.next
            noDuplicatesItr = noDuplicatesItr.next
        return noDuplicatesList

3 个答案:

答案 0 :(得分:0)

您不应显式使用ListNode类。 instance.next也是ListNode的实例,如果不是None的话。我可以想象错误是在while循环条件中得到的:

while (head.next.val != None):

这是不灵活的,因为它要求 head.next不是None,但这不能保证。我可能要做的是检查if node.next is not None

while True:
    if head.next is not None:
        # do something
    else:
        # do something else
        # maybe break or return
    head = head.next

while循环使用while True被认为更具Python风格,并让一些内部控制流指示循环何时中断

答案 1 :(得分:0)

使用示例输入来调试代码 1->1->2


while (head.next.val != None):
  if (head.val != head.next.val):
      noDuplicatesItr.next = ListNode(head.next.val)
  head = head.next
  noDuplicatesItr = noDuplicatesItr.next # this line cause problem

在第一个循环中,分配给noDuplicatesItr的{​​{1}}和noDuplicatesItr.next的值为noDuplicatesItr.next

在第二个循环中,如果条件为True,但语句变为None

这是我根据您的方法接受的解决方案:

None.next = ....

答案 2 :(得分:-1)

一种蛮力解决方案。

try:
  head = head.next
except:
  continue