删除链表元素



我在开始循环之前已经定义了curr,所以它为什么会给我带来一个错误:"NoneType对象没有特性"next"?

class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
curr = head
while curr:
if head.val != curr.val: #if searching val is not first val of list
if curr.val == val:
prev.next = curr.next
# curr = temp.next
else:                         # if seraching val is first val of list
temp = curr
curr.next = None
curr = temp.next
prev = curr
curr = curr.next # this line is getting error
return head

之所以会发生这种情况,是因为当执行else块时,您会使curr等于None,因为您设置了temp.next = None并使curr等于temp:

else:
temp = curr
curr.next = None # This sets `temp.next` to `None` as `temp == curr`
curr = temp.next  # ...so now `curr` is None
# ...
curr = curr.next # ...and then this line will raise an exception...

关于你的代码的其他一些评论:

  • 使用head.val != curr.val,您假设列表中的所有值都是唯一的。如果不是这样的话,你可能会得到一个假阴性。您应该只比较引用:head != curr。然而,我建议执行一个单独的循环来处理需要删除head节点的情况。

  • 您的代码永远不会更新head。然而,当当前的head与值匹配时(即else的情况(,实际上应该使用head = head.next更新head

这是您更正的代码:

class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
# You can deal with the boundary case in a separate loop
while head:
if head.val == val:
head = head.next
if head:
# Now let prev follow behind curr
prev = head
curr = head.next
while curr:
if curr.val == val:
prev.next = curr.next
curr.next = None
else:
prev = curr
curr = prev.next
return head

最新更新