LeetCode 2 两数相加 python

题目描述

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
样例

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)  实际是[2,4,3] [5,6,4]
输出:7 -> 0 -> 8   实际是[7,0,8]
原因:342 + 465 = 807

想法一: 将链表数据取出放入list,然后操作list,再生成链表。比较基础的做法,时间复杂度比较高。

class Solution:
    def getNum(self, testList):
        """
        :type testList: list
        """
        try:
            num = testList.pop(0)
        except IndexError:
            num = 0
        return num

    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        '''
        遍历链表,把数存在列表,然后列表操作之后再创建新链表
        '''
        list1 = []
        list2 = []
        list3 = []
        while l1:
            list1.append(l1.val)
            l1 = l1.next
        while l2:
            list2.append(l2.val)
            l2 = l2.next
        n1 = self.getNum(list1)
        n2 = self.getNum(list2)
        n3 = 0
        while True:
            if n1+n2+n3 > 9:
                list3.append((n1+n2+n3) % 10)
                n3 = 1
            else:
                list3.append(n1+n2+n3)
                n3 = 0
            if list1.__len__() is 0 and list2.__len__() is 0:
                if n3 is 1:
                    list3.append(1)
                break
            n1 = self.getNum(list1)
            n2 = self.getNum(list2)
        n = len(list3)
        for i in range(n):
            if i == 0:
                h3 = ListNode(list3[i])
                l3 = h3
            else:
                l3.next = ListNode(list3[i])
                l3 = l3.next
        l3.next = None
        return h3

想法二: 在遍历链表的同时,计算并且生成新链表,并且sum和carry运用的比较巧妙

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        # 两种特殊情况
        if l1 is None:
            return l2
        if l2 is None:
            return l1
        head = ListNode(0)
        l = head
        carry = 0
        # 当两个链表为空并且无进位,则退出循环
        while l1 or l2 or carry:
            # 每次循环开始,将进位给sum,并且进位清零
            sum, carry = carry, 0
            if l1 is not None:
                sum += l1.val
                l1 = l1.next
            if l2 is not None:
                sum += l2.val
                l2 = l2.next
            # 如果sum大于9,则进位
            if sum > 9:
                carry = 1
                sum -= 10
            # 创建新节点
            l.next = ListNode(sum)
            l = l.next
        return head.next

最后

刷过的LeetCode源码放在Github上了,希望喜欢或者觉得有用的朋友点个star或者follow。
有任何问题可以在下面评论或者通过私信或联系方式找我。
联系方式
QQ:791034063
Wechat:liuyuhang791034063
CSDN:https://blog.csdn.net/Sun_White_Boy
Github:https://github.com/liuyuhang791034063

原文地址:https://www.cnblogs.com/GF66/p/9785472.html