445. Add Two Numbers II Python

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7  

首先简单看下题目,这是反转链表后相加重新组成链表(超过10则只保存个位数再进1到下一位)

以下介绍两种Python解法,第一中用到了两个队列,第二种是用字符串

注意题目要求我们不允许反转链表,所以我们换一种思路

1.队列解法

class Solution:
    def addTwoNumbers(self, l1, l2):
        s1,s2 = [],[]
        while l1:
            s1.append(l1)
            l1 = l1.next
        while l2:
            s2.append(l2)
            l2 = l2.next
        s = 0
        dummy = ListNode(0)
        while s1 or s2 or s:
            if s1:
                s += s1.pop().val
            if s2:
                s += s2.pop().val
            cur = ListNode(s % 10)
            cur.next = dummy.next
            dummy.next = cur
            s //= 10
        return dummy.next

1.一开始保存两个链表的各个结点(为了后续相加计算)

2.dummy是我们创建的一个值为0的结点,它的作用是保证之后的链表不会断开

3.之后就从末端往头遍历,如果超过10则用%保留余数(一开始我用的是-10,万能的disscuss区!)

4.最后一个while循环为什么要把s加入判断呢?因为当想个节点的值相加超过10则要往前面添加1

比如[5] [5]  如果我们没有加入这个条件判断。得到的结果是[0],加了才符合题目变成[1,0]

当s=0是返回False,s!=0返回True

2.字符串解法

class Solution:
    def addTwoNumbers(self, l1, l2):
        s = self.convert(l1) + self.convert(l2)
        return self.MergeList(s)
    
    def convert(self,li):
        s = ''
        while li:
            s += str(li.val)
            li = li.next
        return int(s)
    
    def MergeList(self,s):
        arr = list(str(s))
        head = cur = ListNode(0)
        for i in arr:
            cur.next = ListNode(int(i))
            cur = cur.next
        return head.next

1.我们先创建一个convert函数把我们链表中的值以string的形式相加,最后返回int类型。比如[1,2,3,4]先转换成'1234'在转换成整数1234。两个链表都完成转换后就可以进行相加。优点是最后我们不需要去考虑是否需要做进一位的计算,比如[5] [5] 就变成 [10],再通过下一个函数转换成单个元素。

2.之后就要对这两个链表的值进行合并了。比如s=12345,先转换成str再转成list就变成了['1','2','3','4','5']

余下的工作就是把这些值换成int并创建结点,重新组成链表。

时间复杂度为 O(n)  空间复杂度为O(n)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值