I am trying to run the below code, I expect the code to return a list called head which would contain sum of (first and second) where first and second is linked lists passed as an argument.
As you see at the end I have created two linked List l1
and l2
. I am assuming this linked lists will inherit from the Node
class.
But it gives an attribute error. I can't seem to figure out the problem. I am a novice in programming, self learner. What might be causing this error? How do we go about solving it?
class Node:
def __init__(self,data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def display(self):
elems = []
current = self.head
while current != None:
elems.append(current.data)
current = current.next
return elems
def append(self, data):
elem = Node(data)
if self.head == None:
self.head = elem
else:
current = self.head
while current.next != None:
current = current.next
current.next = elem
def addTwoLists(self, first, second):
head = third = Node(0)
carry = 0
while first or second or carry:
if first:
carry += first.data
first = first.next
if second:
carry += second.data
second = second.next
third.data = carry % 10
carry = carry // 10
if first or second or carry:
third.next = Node(0)
third = third.next
return head
ll = LinkedList()
list1 = LinkedList()
list2 = LinkedList()
list1.append(7)
list1.append(1)
list1.append(6)
print(list1.display())
list2.append(5)
list2.append(9)
list2.append(2)
print(list2.display())
ll.addTwoLists(list1,list2)
print(ll.display())
And the error I get it:
carry += first.data
AttributeError: 'LinkedList' object has no attribute 'data'