• 首先反转需要相加的两个链表
  • 其次每次新建节点tmp,把tmp.next -> res; 然后res = tmp
class Solution:
    def reverseList(self, head):
        res = None
        cur = head
        while cur:
            tmp = cur.next
            cur.next = res
            res = cur 
            cur = tmp
        return res

    def addInList(self, head1, head2):
        # write code here
        rhead1 = self.reverseList(head1)
        rhead2 = self.reverseList(head2)
        rp1, rp2 = rhead1, rhead2
        carry = 0
        res = None
        while rp1 or rp2:
            val1 = rp1.val if rp1 is not None else 0
            val2 = rp2.val if rp2 is not None else 0
            carry, val = divmod(val1 + val2 + carry, 10)
            tmp = ListNode(val)
            tmp.next = res
            res = tmp
            if rp1:
                rp1 = rp1.next
            if rp2:
                rp2 = rp2.next

        if carry > 0:
            tmp = ListNode(carry)
            tmp.next = res
            res = tmp
        return res