-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathAdd_Two_Numbers.py
More file actions
61 lines (53 loc) · 1.73 KB
/
Add_Two_Numbers.py
File metadata and controls
61 lines (53 loc) · 1.73 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
49
50
51
52
53
54
55
56
57
58
59
60
61
"""
@author - Anirudh Sharma
"""
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:
# Head of the new linked list - this is the head of the resultant list
head = None
# Reference of head which is null at this point
temp = None
# Carry
carry = 0
# Loop for the two lists
while l1 is not None or l2 is not None:
# At the start of each iteration, we should add carry from the last iteration
sum_value = carry
# Since the lengths of the lists may be unequal, we are checking if the
# current node is null for one of the lists
if l1 is not None:
sum_value += l1.val
l1 = l1.next
if l2 is not None:
sum_value += l2.val
l2 = l2.next
# At this point, we will add the total sum_value % 10 to the new node
# in the resultant list
node = ListNode(sum_value % 10)
# Carry to be added in the next iteration
carry = sum_value // 10
# If this is the first node or head
if temp is None:
temp = head = node
# for any other node
else:
temp.next = node
temp = temp.next
# After the last iteration, we will check if there is carry left
# If it's left then we will create a new node and add it
if carry > 0:
temp.next = ListNode(carry)
return head
head1 = ListNode(2)
head1.next = ListNode(4)
head1.next.next = ListNode(3)
head2 = ListNode(5)
head2.next = ListNode(6)
head2.next.next = ListNode(4)
result = addTwoNumbers(head1, head2)
while result is not None:
print(str(result.val), end=" ")
result = result.next