-
Notifications
You must be signed in to change notification settings - Fork 181
/
Copy pathadd_two_integers.py
66 lines (59 loc) · 1.18 KB
/
add_two_integers.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
"""
Problem Statement
Given the head pointers of two linked lists where each linked list represents an integer number (each node is a digit),
add them and return the resulting linked list. Here, the first node in a list represents the least significant digit.
"""
class Node:
def __init__(self, value):
self.value = value
self.next = None
def sum_lists(l1, l2):
c = 0
l3 = None
while l1 or l2:
v1 = 0
v2 = 0
if l1:
v1 = l1.value
l1 = l1.next
if l2:
v2 = l2.value
l2 = l2.next
r = v1 + v2 + c
c = r // 10
d = r % 10
if not l3:
l3 = Node(d)
p3 = l3
else:
p3.next = Node(d)
p3 = p3.next
return l3
def print_list(l):
while l:
print("{}->".format(l.value), end = '')
l = l.next
def print_number(l):
stack = []
while l:
stack.append(l.value)
l = l.next
while len(stack) > 0:
v = stack.pop()
print("{}".format(v), end = '')
def create_linked_list(list_numbers):
l = None
for n in list_numbers:
if not l:
l = Node(n)
p = l
else:
p.next = Node(n)
p = p.next
return l
first = create_linked_list([1, 2, 3]) #321
second = create_linked_list([1, 2]) #21
print("Sum:", end='')
r = sum_lists(first, second)
print_number(r)
print()