[英]Issue with Reverse Link List - Leetcode Problem NoneType Error
我正在嘗試根據這個 leetcode 問題反轉鏈接列表: ReverseLL
我的代碼:
# 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
"""
cur = head
nxt = cur.next
while nxt != None:
temp = nxt.next
nxt.next = cur
cur = nxt
nxt = temp
head.next = None
head = cur
return head
但是,我在行中收到屬性錯誤:
nxt = cur.next
錯誤信息: AttributeError: 'NoneType' object has no attribute 'next'
但是我不太確定為什么當我將 cur 指定為 head 時它是 noneType?
這里的問題是,您試圖在將 cur 初始化為head
后立即訪問cur
的next
屬性,而不先檢查head
是否為None
。 因此,如果reverseList
的任何輸入為空,都會導致您的情況出現Attribute error
。
您可以在 while 循環之前檢查head
是否為None
的情況。
if head is None:
return None
因為 head 也可以是 None,所以在賦值之前做
if head is None:
return head
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.