簡體   English   中英

反向鏈接列表問題 - Leetcode 問題 NoneType 錯誤

[英]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后立即訪問curnext屬性,而不先檢查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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM