LeetCode445: 两数相加 II

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

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

示例:

输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7
class LinkNode():
    def __init__(self, value, next = None):
        self.value = value
        self.next = next

class Solution():
    def countPlusValue(self, headA:LinkNode, headB:LinkNode) -> LinkNode:
        if headA is None: return
        if headB is None: return

        list1, list2 = [], []
        while headA:
            list1.append(headA.value)
            headA = headA.next

        while headB:
            list2.append(headB.value)
            headB = headB.next

        newNode = None
        remainder = 0
        while list1 or list2 or remainder != 0: # remainder = 0是为了最高位两位数相加大于10需要进位,但此时list1和list2已经为空,需要此判断条件
            a = 0 if not list1 else list1.pop()
            b = 0 if not list2 else list2.pop()

            value = a + b + remainder
            remainder = value // 10
            value = value % 10
            curNode = LinkNode(value, newNode)
            newNode = curNode

        return  newNode

# 生成A链表
headA1 = LinkNode(3, None)
headA2 = LinkNode(4, headA1)
headA3 = LinkNode(2, headA2)
headA4 = LinkNode(7, headA3)

# 生成B链表
headB1 = LinkNode(4, None)
headB2 = LinkNode(6, headB1)
headB3 = LinkNode(5, headB2)

solu = Solution()
plusValue = solu.countPlusValue(headA4, headB3)
print(plusValue)

时间复杂度:O(max(m,n))

空间复杂度:O(m,n)

你可能感兴趣的:(数据结构与算法)