Leetcode 问题 21:我的代码出现 NoneType 错误,而解决方案却没有。这是为什么?

问题描述 投票:0回答:1

我目前正在尝试解决LeetCode问题Nr。 21. 我是 Python 课程的新手,不明白以下内容:

我的代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        if list1.val <= list2.val:
            print("HI")
        return ListNode()

有这个运行时错误:

AttributeError: 'NoneType' object has no attribute 'val'
    if list1.val<=list2.val:
Line 8 in mergeTwoLists (Solution.py)
    ret = Solution().mergeTwoLists(param_1, param_2)
Line 34 in _driver (Solution.py)
    _driver()
Line 45 in <module> (Solution.py)

我知道该问题的一种解决方案是以下代码:

class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        cur = dummy = ListNode()
        while list1 and list2:               
            if list1.val < list2.val:
                cur.next = list1
                list1, cur = list1.next, list1
            else:
                cur.next = list2
                list2, cur = list2.next, list2
                
        if list1 or list2:
            cur.next = list1 if list1 else list2
            
        return dummy.next

从我的角度来看,这里唯一的区别是,

if list1.val <= list2.val:
位于 while 循环内。为什么这会有所不同?

python linked-list nonetype
1个回答
0
投票

正如 Bamar 所指出的:

Optional[ListNode] 意味着该值可以是 None 而不是实际的 ListNode 对象。在尝试访问属性之前,您需要检查这一点。

事实证明,其中一个测试用例正是一个 None 对象。我完全忘记了。

© www.soinside.com 2019 - 2024. All rights reserved.