You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+42
Original file line number
Diff line number
Diff line change
@@ -339,4 +339,46 @@ The only hop here is that we have to handle the None tails of the lists we're tr
339
339
340
340
##### Optimal solution
341
341
342
+
If we are a little more smart — and want to deal with linked list back and forth pointers — we can do it in a single iteration.
342
343
344
+
```python
345
+
defaddTwoNumbers(self, l1, l2):
346
+
# we need to initiate a dummy head so that
347
+
# we can freely add new elements in the while loop
348
+
# then we just drop this first node, and return
349
+
# ones holding correct numbers
350
+
ll_head = ListNode(0, None)
351
+
tail = ll_head
352
+
carry =0
353
+
354
+
# why do we need the carry condition? the last
355
+
# summation can yield a carry, so even though
356
+
# we'll be finished with lists, we still have
357
+
# to append carry
358
+
while l1 isnotNoneor l2 isnotNoneor carry !=0:
359
+
v1 = l1.val if l1 isnotNoneelse0
360
+
v2 = l2.val if l2 isnotNoneelse0
361
+
362
+
number = carry + v1 + v2
363
+
digit = number %10
364
+
carry = number //10
365
+
366
+
# back and forth ll shenanigans that allow
367
+
# squishing it into a single loop
368
+
# basically, we keep hold of the first element
369
+
# because we need it for the return
370
+
# and iteratively move the tail, so we can
371
+
# add new elements as well
372
+
node = ListNode(digit)
373
+
tail.next = node
374
+
tail = tail.next
375
+
376
+
# thanks to this, we can skip checks like l1.next.next
377
+
l1 = l1.next if l1 isnotNoneelseNone
378
+
l2 = l2.next if l2 isnotNoneelseNone
379
+
380
+
r = ll_head.next
381
+
return r
382
+
```
383
+
384
+
Funnily, my solution is basically the exact same solution that's available on the solutions page. Of course I am looking there for help when I'm really stuck, but this time I wrote it and was like "OH MY GOD ITS MY CODE THERE, ARE WE THE SAME PERSON!?". The comments should point you at what we are trying to do with all the nodes, you may need to ponder for a bit and it'll click. If not, then take the ListNode class and play with it. You'll get it.
0 commit comments