Skip to content

Commit 4303d80

Browse files
committed
Sum Lists
1 parent 5a0f9e7 commit 4303d80

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

linked-lists/sum-lists.py

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
"""
2+
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse
3+
order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as
4+
the linked list.
5+
6+
Example:
7+
Input: (7 -> 1 -> 6) + (5 -> 9 -> 2). That is, 617 + 295.
8+
Output: 2 -> 1 -> 9. That is, 912.
9+
10+
FOLLOW UP:
11+
Suppose the digits are stored in forward order. Repeat the above problem.
12+
Input: (6 -> 1 -> 7) + (2 -> 9 -> 5). That is, 617 + 295.
13+
Output: 9 -> 1 -> 2. That is, 912.
14+
"""
15+
def addTwoNumbers(l1, l2):
16+
res = ListNode(0)
17+
cur = res
18+
carry = 0
19+
while l1 or l2:
20+
x = l1.val if l1 else 0
21+
y = l2.val if l2 else 0
22+
summ = carry + x + y
23+
carry = summ // 10
24+
cur.next = ListNode(summ%10)
25+
cur = cur.next
26+
if l1:
27+
l1 = l1.next
28+
if l2:
29+
l2 = l2.next
30+
if carry > 0:
31+
cur.next = ListNode(carry)
32+
return res.next
33+
34+
""" Follow Up """
35+
class Solution(object):
36+
def addTwoList(self, l1, l2):
37+
len1,len2 = self.getLength(l1),self.getLength(l2)
38+
if len1 > len2:
39+
l2 = self.addLeadingZeroes(len1-len2,l2)
40+
else:
41+
l1 = self.addLeadingZeroes(len2-len1,l1)
42+
carry, summ = self.addNumbers(l1,l2)
43+
if carry > 0:
44+
new = ListNode(carry)
45+
new.next = summ
46+
summ = new
47+
return summ
48+
49+
def getLength(self, node):
50+
count = 0
51+
while node:
52+
count += 1
53+
node = node.next
54+
return count
55+
56+
def addLeadingZeroes(self,count,node):
57+
for i in range(count):
58+
new = ListNode(0)
59+
new.next = node
60+
node = new
61+
return node
62+
63+
def addNumbers(self,l1,l2):
64+
if not l1 and not l2:
65+
return (0,None)
66+
carry,new = self.addNumbers(l1.next,l2.next)
67+
summ = l1.val + l2.val + carry
68+
ans = ListNode(summ%10)
69+
ans.next = new
70+
return (summ//10,ans)

0 commit comments

Comments
 (0)