0

I am trying to add two LinkedLists together but I keep receiving an error saying:

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

I understand my code may be wrong algorithmically, but I cannot get around this one error. I have tried removing the .val but that throws a different error and I have printed l1.val and l2.val before the while loop and it prints without error. The following is the definition for the LinkedList class provided and my code.

# 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
0

1 Answer 1

2

temp is an int, but you assign it to output.next, which will cause the error you see when it is used as a ListNode.

Sign up to request clarification or add additional context in comments.

2 Comments

output.val = temp?
Sorry for the confusion. I understand now. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.