两数相加

两数相加:

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)输出:7 -> 0 -> 8原因:342 + 465 = 807

#!/user/bin/env python

# _*_ coding:utf-8 _*_

# __author__ :"ChenJH"

# Date:2018/5/8

class ListNode:

    def __init__(self, x):

    self.val = x

    self.next =None

class Solution:

    ee =0

    def addTwoNumbers1(self, l1, l2):

        t =int((l1.val + l2.val +self.ee) /10)

        l2.val = (l2.val + l1.val +self.ee) %10

        self.ee = t

        if l1.nextand l2.next:

            self.addTwoNumbers1(l1.next, l2.next)

        elif l1.next :

            l2.next = ListNode(0)

            self.addTwoNumbers1(l1.next, l2.next)

        elif l2.next:

            l1.next = ListNode(0)

            self.addTwoNumbers1(l1.next, l2.next)

        elif self.ee==1:

            n = ListNode(self.ee)

            l2.next=n

    return l2

你可能感兴趣的:(两数相加)