我正在尝试将两个LinkedLists一起添加,但是我一直收到错误消息:
AttributeError: 'int' object has no attribute 'val'
我了解我的代码在算法上可能是错误的,但是我无法解决这一错误。我尝试删除.val
,但是会引发不同的错误,并且我在while循环之前打印了l1.val
和l2.val
,并且打印时没有错误。以下是提供的LinkedList
类的定义和我的代码。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
output = ListNode(None)
while l1:
temp = l1.val + l2.val
if temp > 9:
temp -= 10
l1 = l1.next.val + 1
else:
l1 = l1.next
output.next = temp
l2 = l2.next
temp
是int
,但是将其分配给output.next
,这将导致在将其用作ListNode
时看到错误。