最近在刷题【牛客剑指offer刷题】:Python:18. 删除链表的节点
时,遇到这样一个问题,由于写错了一句话导致怎么也不通过,最后发现原来是判断 int 为 0 时判断为 False 了, 这里记录一下:
输入:{2, 3, 4, 0, 1}, 0
错误的代码:class Solution:
def deleteNode(self , head: ListNode, val: int) -> ListNode:
# write code here
# 注意:这里的val如果为0 的话那么判断not val就是TRUE
if not head or not val:
return None
if head.val == val:
return head.next
pre, cur = None, head
while cur:
if cur and cur.val == val:
cur = pre
cur.next = cur.next.next
else:
pre = cur
cur = cur.next
return head
错误的输出:{}
正确的代码:class Solution:
def deleteNode(self , head: ListNode, val: int) -> ListNode:
# write code here
# 注意:这里的val如果为0 的话那么判断val is None就是False
if not head or val is None:
return head
if head.val == val:
return head.next
pre, cur = None, head
while cur:
if cur and cur.val == val:
cur = pre
cur.next = cur.next.next
else:
pre = cur
cur = cur.next
return head
正确输出:{4,1,9}
总结:以后需要判断 int 变量是否是None值时:不能使用if not val而应该使用if val is None。



