Leetcode002 add-two-numbers

两数相加

题目描述:

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

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

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

示例:


输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)

输出:7 -> 0 -> 8

原因:342 + 465 = 807


解题思路:

 这里是对这两个链表进行的遍历,可以认为两个链表的长度一样长(此时如果不一样长,可以在短的那条链表后面补上0)。然后对每一位的节点进行相加,最后反向输出即可。特别注意的是进位问题。如果有进位,则在下一个节点的位置初始化为ListNode(1)即可。


Python源码:

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        result = ListNode(0);
        curr = result;
        while l1 or l2:
            curr.val += self.addTwoNodes(l1, l2)
            if curr.val >= 10:
                curr.val -= 10
                curr.next = ListNode(1)
            else:
                # 判断是否链表已经结束了
                if l1 and l1.next or l2 and l2.next:
                    curr.next = ListNode(0)
            curr = curr.next
            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next
        return result

    def addTwoNodes(self, l1, l2):
        if not l1 and not l2:
            None
        if not l1:
            return l2.val
        if not l2:
            return l1.val
        return l1.val + l2.val

欢迎关注我的github:https://github.com/UESTCYangHR

猜你喜欢

转载自blog.csdn.net/dzkdyhr1208/article/details/89018354