2. Add Two Numbers
Question
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.Time Complexity
Code
class Solution:
def addTwoNumbers(self, l1, l2):
if l1 == None or l2 == None:
return l2 if l1 == None else l1
head = l1
pre, c = None, 0
while l1 and l2:
s = l1.val + l2.val + c #sum
l1.val = s % 10
c = x // 10
l1 = l1.next
l2 = l2.next
pre = head if pre == None else pre.next
if l1 == None:
pre.next = l2
left = pre.next
while left != None:
x = left.val + c
left.val = x % 10
c = x // 10
left = left.next
pre = pre.next #keep tracking in case left == null
if c == 1:
pre.next = ListNode(1)
return headLast updated