首页 > 代码库 > Add Two Numbers

Add Two Numbers

题目如下:

技术分享

Python代码:

# Definition for singly-linked list.class ListNode(object):    def __init__(self, x):        self.val = x        self.next = Noneclass Solution(object):    def addTwoNumbers(self, l1, l2):        """        :type l1: ListNode        :type l2: ListNode        :rtype: ListNode        """        head = ListNode(1)        current = ListNode(1)        head.next = current        flag = 0        while l1!=None and l2!=None:            sum = l1.val+l2.val+flag            if sum<10:                flag = 0                current.next = ListNode(sum)            else:                flag = 1                current.next = ListNode(sum-10)            current = current.next            l1 = l1.next            l2 = l2.next        if l1==None and l2!=None:            print "in"            while l2!=None:                if flag==0:                    current.next = ListNode(l2.val)                else:                    if l2.val+1<10:                        flag = 0                        current.next = ListNode(l2.val+1)                    else:                        flag = 1                        current.next = ListNode(l2.val-9)                l2 = l2.next                current = current.next        if l1!=None and l2==None:            print "out"            while l1!=None:                if flag==0:                    current.next = ListNode(l1.val)                else:                    if l1.val+1<10:                        flag = 0                        current.next = ListNode(l1.val+1)                    else:                        flag = 1                        current.next = ListNode(l1.val-9)                l1 = l1.next                current=current.next        if flag == 1:            current.next = ListNode(1)        return head.next.nexta = ListNode(1)b = ListNode(9)b.next = ListNode(9)c = Solution()c.addTwoNumbers(a,b)

 

Add Two Numbers