首页 > 解决方案 > 链表 while 语句(来自 LeetCode 的 addTwoNumbers)

问题描述

以下是我提交并随后被接受的代码。

class Solution(object):
def addTwoNumbers(self, l1, l2):
    """
    :type l1: ListNode
    :type l2: ListNode
    :rtype: ListNode
    """
    result = ListNode(0)
    result_tail = result
    carry = 0

    while l1 or l2 or carry:        

        val1  = (l1.val if l1.val else 0)
        val2  = (l2.val if l2.val else 0)

        out = (val1+val2 + carry)%10
        carry = (val1+val2 + carry)//10

        result_tail.next = ListNode(out)
        result_tail = result_tail.next                      

        l1 = (l1.next if l1.next else None)
        l2 = (l2.next if l2.next else None)

    return result.next 

最初,我有,while l1.val or l2.val or carry:但它被拒绝并显示以下错误消息:

AttributeError:“NoneType”对象具有 njo 属性“val”

但是,链接节点列表 l1 和 l2 显然具有属性 val 和 next。

我不知道为什么while l1.val or l2.val or carry:没有工作。

下面是我最初提交但被拒绝的代码。

class Solution(object):
def addTwoNumbers(self, l1, l2):
    """
    :type l1: ListNode
    :type l2: ListNode
    :rtype: ListNode
    """
    result = ListNode(0)
    result_tail = result
    carry = 0

    print(l1.val)
    print(l2.val)
    while l1.val or l2.val or carry:        

        val1  = (l1.val if l1.val else 0)
        val2  = (l2.val if l2.val else 0)

        out = (val1+val2 + carry)%10
        carry = (val1+val2 + carry)//10

        result_tail.next = ListNode(out)
        result_tail = result_tail.next                      

        l1 = (l1.next if l1.next else None)
        l2 = (l2.next if l2.next else None)

    return result.next 

标签: pythonsingly-linked-list

解决方案


可能有一个测试用例,其中 l1 和/或 l2 的传入值为 None。如果发生这种情况,则会引发 AttributeError ,因为 None 没有任何此类属性 - 它只是 None (在其他语言中为 null)。

请注意,您通过简单地从 while 语句中的每个 l1 和 l2 中删除 .val 来解决了检查 None 的问题。这就是第二次提交成功接受的原因。


推荐阅读