@@ -181,7 +181,6 @@ def sum_lists(ll1: LinkedList, ll2: LinkedList) -> LinkedList:
181
181
"""
182
182
Will add ll1 and ll2 where each element in the linked lists
183
183
represent digits.
184
- Precondition: ll1 and ll2 must be the same length.
185
184
Digits are in backward order, for example:
186
185
Input: (7 -> 1 -> 6) + (5 -> 9 -> 2). That is, 617 + 295
187
186
Result: 2 -> 1 -> 9. That is, 912
@@ -191,9 +190,9 @@ def sum_lists(ll1: LinkedList, ll2: LinkedList) -> LinkedList:
191
190
:param ll2: second input linked list
192
191
:return: a linked list containing the result of the addition
193
192
"""
194
- assert (ll1 .size == ll2 .size )
195
- n1 = ll1 .head
196
- n2 = ll2 .head
193
+ shorter_ll , longer_ll = (ll1 , ll2 ) if ll1 .size < ll2 .size else ( ll2 , ll1 )
194
+ n1 = shorter_ll .head
195
+ n2 = longer_ll .head
197
196
output_ll = LinkedList ()
198
197
carry = 0
199
198
while n1 is not None :
@@ -208,6 +207,17 @@ def sum_lists(ll1: LinkedList, ll2: LinkedList) -> LinkedList:
208
207
output_ll .append_to_tail (result )
209
208
n1 = n1 .next
210
209
n2 = n2 .next
210
+ # loop through remaining longer list
211
+ while n2 is not None :
212
+ value = n2 .data
213
+ result = value + carry
214
+ if result >= 10 :
215
+ carry = 1
216
+ result -= 10
217
+ else :
218
+ carry = 0
219
+ output_ll .append_to_tail (result )
220
+ n2 = n2 .next
211
221
if carry > 0 :
212
222
output_ll .append_to_tail (carry )
213
223
return output_ll
@@ -246,6 +256,21 @@ def setUp(self):
246
256
LinkedList (9 , 9 , 9 , 9 ),
247
257
LinkedList (9 , 9 , 9 , 9 ),
248
258
LinkedList (8 , 9 , 9 , 9 , 1 )
259
+ ),
260
+ (
261
+ LinkedList (9 , 9 , 9 , 9 ),
262
+ LinkedList (9 , 9 ),
263
+ LinkedList (8 , 9 , 0 , 0 , 1 )
264
+ ),
265
+ (
266
+ LinkedList (1 , 2 ),
267
+ LinkedList (1 ),
268
+ LinkedList (2 , 2 )
269
+ ),
270
+ (
271
+ LinkedList (5 ),
272
+ LinkedList (2 , 1 ),
273
+ LinkedList (7 , 1 )
249
274
)
250
275
]
251
276
0 commit comments