给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

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

示例:

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

输入:(2 -> 3) + (0)
输出:2 -> 3
原因:32 + 0 = 32

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

def create_list(nums):
    last = None
    for num in reversed(nums):
        list_node = ListNode(num)
        list_node.next = last
        last = list_node
    return last

class Solution(object):
    # 直接对两个链表操作;对应节点上的值做加法运算,过10则进位。位数不够则补0
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        l = ListNode(0)
        l_copy = l
        # 定义两数相加是否大于10进位
        carry = 0
        while l1 or l2:
            # 因为l1与l2链表对应的位数可能不同,此时需要将空缺的位置补0
            l1_val = l1.val if l1 else 0
            l2_val = l2.val if l2 else 0
            two_sum = l1_val + l2_val + carry
            if two_sum < 10:
                l_copy.next = ListNode(two_sum)
                carry = 0
            else:
                carry = two_sum//10
                l_copy.next = ListNode(two_sum%10)
            l_copy = l_copy.next
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        if carry > 0:
            l_copy.next = ListNode(1)
        return l.next

if __name__ == "__main__":
    l1 = create_list([3, 4, 7])
    l2 = create_list([6, 4])
    s = Solution()
    a = s.addTwoNumbers(l1, l2)
    while a:
        print(a.val)
        a=a.next

来源:leetcode

Posted on 2019-07-07 23:18  少说话多读书  阅读(108)  评论(0编辑  收藏  举报