试图将两个链表一起添加,但出现AttributeError

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

我正在尝试将两个LinkedLists一起添加,但是我一直收到错误消息:

AttributeError: 'int' object has no attribute 'val'

我了解我的代码在算法上可能是错误的,但是我无法解决这一错误。我尝试删除.val,但是会引发不同的错误,并且我在while循环之前打印了l1.vall2.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
python
1个回答
2
投票
[tempint,但是将其分配给output.next,这将导致在将其用作ListNode时看到错误。
© www.soinside.com 2019 - 2024. All rights reserved.