- See Code
O(n)
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
"""
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
s1 = 0
s2 = 0
while l1:s1 *= 10; s1 += l1.val; l1 = l1.next
while l2: s2 *= 10; s2 += l2.val; l2 = l2.next
# take the sum and reconstruct the number from tail to head, because it's easier
# to isolate and chop off the little digits with modulus and division.
s3 = s1 + s2
tail = None
head = None
while s3 > 0: head = ListNode(s3 % 10); head.next = tail; tail = head; s3 //= 10
return head if head else ListNode(0)