Skip to content

Commit d7abf11

Browse files
committed
2: completed
1 parent 34c545d commit d7abf11

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

README.md

+42
Original file line numberDiff line numberDiff 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
339339

340340
##### Optimal solution
341341

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.
342343

344+
```python
345+
def addTwoNumbers(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 is not None or l2 is not None or carry != 0:
359+
v1 = l1.val if l1 is not None else 0
360+
v2 = l2.val if l2 is not None else 0
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 is not None else None
378+
l2 = l2.next if l2 is not None else None
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

Comments
 (0)