-
Notifications
You must be signed in to change notification settings - Fork 0
/
addTwoNumbers.py
56 lines (48 loc) · 1.21 KB
/
addTwoNumbers.py
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
49
50
51
52
53
54
55
from list import LinkedList
from list import Node
def add(a, b):
result = LinkedList()
lastNode = None
carry = 0
while a and b:
sum = a.data + b.data + carry
if lastNode:
lastNode.next = Node(sum % 10)
lastNode = lastNode.next
else:
result.head = Node(sum % 10)
lastNode = result.head
carry = sum / 10
a, b = a.next, b.next
while a:
sum = a.data + carry
if lastNode:
lastNode.next = Node(sum % 10)
lastNode = lastNode.next
else:
result.head = Node(sum % 10)
lastNode = result.head
carry = sum / 10
a = a.next
while b:
sum = b.data + carry
if lastNode:
lastNode.next = Node(sum % 10)
lastNode = lastNode.next
else:
result.head = Node(sum % 10)
lastNode = result.head
carry = sum / 10
b = b.next
if carry == 1:
if lastNode:
lastNode.next = Node(1)
else:
result.head = Node(1)
return result
a = LinkedList()
a.append(6)
a.append(7)
a.append(5)
b = LinkedList()
add(a.head, b.head).printList()