Skip to content

Commit b3117b4

Browse files
add_two_numbers
1 parent 65a77e2 commit b3117b4

File tree

3 files changed

+131
-3
lines changed

3 files changed

+131
-3
lines changed

.idea/workspace.xml

Lines changed: 76 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Binary file not shown.

Leetcode/add_two_numbers.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
from DataStructures.LinkedList.LinkedList import LinkedList
2+
from DataStructures.LinkedList.LinkedList import Node
3+
4+
5+
def add_two_numbers(l1: Node, l2: Node) -> Node:
6+
head = None
7+
current_node = None
8+
carry = 0
9+
10+
while (l1 is not None) or (l2 is not None) or (carry > 0):
11+
total = carry
12+
13+
# case 1: When we have both nodes
14+
if (l1 is not None) and (l2 is not None):
15+
total += (l1.data + l2.data)
16+
l1 = l1.next
17+
l2 = l2.next
18+
19+
# case 2: When one of the nodes is None
20+
elif l1 is None:
21+
total += l2.data
22+
l2 = l2.next
23+
24+
elif l2 is None:
25+
total += l1.data
26+
l1 = l1.next
27+
28+
# Calculating value of the node and carry
29+
val = total % 10
30+
carry = total // 10
31+
new_node = Node(val)
32+
33+
# If it is the first node, save it as head
34+
if head is None:
35+
head = current_node = new_node
36+
else:
37+
current_node.next = new_node
38+
current_node = new_node
39+
40+
return head
41+
42+
43+
l1 = LinkedList()
44+
l1.insert(2)
45+
l1.insert(4)
46+
l1.insert(3)
47+
48+
l2 = LinkedList()
49+
l2.insert(5)
50+
l2.insert(6)
51+
l2.insert(4)
52+
53+
head = add_two_numbers(l1.head, l2.head)
54+
l3 = LinkedList()
55+
l3.print_list(head)

0 commit comments

Comments
 (0)