445 Add Two Numbers II
Python
class Solution(object):
def reverseList(self, head):
prev, curr = None, head
while curr:
t = curr.next
curr.next = prev
prev = curr
curr = t
return prev
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l1 = self.reverseList(l1)
l2 = self.reverseList(l2)
cur, carry = 0, 0
head = ListNode(0)
curNode = head
while l1 or l2:
x = l1.val if l1 else 0
y = l2.val if l2 else 0
cur = x + y + carry
carry = cur / 10
cur = cur % 10
curNode.next = ListNode(cur)
curNode = curNode.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
if carry:
curNode.next = ListNode(carry)
curNode = curNode.next
return self.reverseList(head.next)