提问人:metricspace 提问时间:11/1/2023 最后编辑:metricspace 更新时间:11/1/2023 访问量:51
Python 链表打印问题
Python linked list printing issue
问:
我正在做 leetcode 206 并想打印一些中间结果。我正在使用以下代码。如果我不检查节点是否为无,它会打印但给我错误。
AttributeError: 'NoneType' object has no attribute 'val'
print(curr.val)
Line 16 in reverseList (Solution.py)
ret = Solution().reverseList(param_1)
Line 51 in _driver (Solution.py)
_driver()
Line 61 in <module> (Solution.py)
但是,如果我检查一下,它会打印出没有错误。有人知道为什么会这样吗?
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
curr = head
prev = None
print(curr.val) # this one prints but with error
if curr!=None:
print(curr.val) # this one prints without error
while curr:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return prev
我希望它既有错误,又没有错误。但是什么导致了这种差异呢?
答: 暂无答案
评论
None
val
None
None.val
curr == None
head == None
head==None