-
Notifications
You must be signed in to change notification settings - Fork 0
/
127.py
88 lines (68 loc) · 2.13 KB
/
127.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""
Problem:
Let's represent an integer in a linked list format by having each node represent a
digit in the number. The nodes make up the number in reversed order.
For example, the following linked list:
1 -> 2 -> 3 -> 4 -> 5 is the number 54321.
Given two linked lists in this format, return their sum in the same linked list format.
For example, given
9 -> 9 5 -> 2 return 124 (99 + 25) as:
4 -> 2 -> 1
"""
from DataStructures.LinkedList import LinkedList, Node
def add_linked_lists(ll1: LinkedList, ll2: LinkedList) -> LinkedList:
sum_linked_list = LinkedList()
pos1, pos2 = ll1.head, ll2.head
carry, curr_position_sum = 0, 0
# generating the sum of the linked lists
while pos1 or pos2:
if pos1 == None:
curr_position_sum = pos2.val + carry
if curr_position_sum >= 10:
carry, curr_position_sum = 1, curr_position_sum - 10
else:
carry = 0
elif pos2 == None:
curr_position_sum = pos1.val + carry
if curr_position_sum >= 10:
carry, curr_position_sum = 1, curr_position_sum - 10
else:
carry = 0
else:
curr_position_sum = pos2.val + pos1.val + carry
if curr_position_sum >= 10:
carry, curr_position_sum = 1, curr_position_sum - 10
else:
carry = 0
sum_linked_list.add(curr_position_sum)
# moving to the next value
if pos1:
pos1 = pos1.next
if pos2:
pos2 = pos2.next
if carry == 1:
sum_linked_list.add(1)
return sum_linked_list
def create_linked_list(val: int) -> LinkedList:
LL = LinkedList()
while val > 0:
LL.add(val % 10)
val = val // 10
return LL
if __name__ == "__main__":
LL1 = create_linked_list(99)
LL2 = create_linked_list(25)
print(LL1)
print(LL2)
print(add_linked_lists(LL1, LL2))
print()
LL1 = create_linked_list(9)
LL2 = create_linked_list(250)
print(LL1)
print(LL2)
print(add_linked_lists(LL1, LL2))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(n)
"""