-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddTwoNumbersLL(works)
More file actions
48 lines (48 loc) · 1.35 KB
/
addTwoNumbersLL(works)
File metadata and controls
48 lines (48 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def addTwoLists(self, first, second):
prev = None
temp = None
carry = 0
while(first is not None or second is not None):
fdata = 0 if first is None else first.data
sdata = 0 if second is None else second.data
Sum = carry + fdata + sdata
carry = 1 if Sum >= 10 else 0
Sum = Sum if Sum < 10 else Sum % 10
temp = Node(Sum)
if self.head is None:
self.head = temp
else:
prev.next = temp
prev = temp
if first is not None:
first = first.next
if second is not None:
second = second.next
if carry > 0:
temp.next = Node(carry)
def printList(self):
temp = self.head
while(temp):
print (temp.data,end=' ')
temp = temp.next
first = LinkedList()
second = LinkedList()
first.push(1)
first.push(5)
second.push(3)
second.push(9)
second.push(7)
res = LinkedList()
res.addTwoLists(first.head, second.head)
res.printList()