【发布时间】:2019-12-04 02:18:38
【问题描述】:
以下是我提交并随后被接受的代码。
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
【问题讨论】: