forked from prabhupant/python-ds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsum_of_two_numbers.py
71 lines (54 loc) · 1.29 KB
/
sum_of_two_numbers.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class Node():
def __init__(self, val):
self.val = val
self.next = None
def push(head, data):
node = Node(data)
curr = head
while curr.next:
curr = curr.next
curr.next = node
def print_list(head):
curr = head
while curr:
print(curr.val, end=' ')
curr = curr.next
def sum_numbers(head1, head2):
carry = 0
prev = None
res = None
while head1 is not None or head2 is not None:
data1 = 0 if head1 is None else head1.val
data2 = 0 if head2 is None else head2.val
s = carry + data1 + data2
carry = 1 if s >= 10 else 0
s = s if s < 10 else s % 10
temp = Node(s)
# if this is the first node, make it head
if res is None:
res = temp
else:
prev.next = temp
prev = temp
# move pointers ahead
if head1 is not None:
head1 = head1.next
if head2 is not None:
head2 = head2.next
if carry > 0:
temp.next = Node(carry)
return res
head1 = Node(1)
push(head1, 2)
push(head1, 3)
push(head1, 4)
print_list(head1)
print()
head2 = Node(5)
push(head2, 2)
push(head2, 1)
push(head2, 3)
print_list(head2)
print()
summmed_list = sum_numbers(head1, head2)
print_list(summmed_list)