Python刷leetcode--2.两数相加 [链表]

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        # leetcode submit region end(Prohibit modification and deletion)

        ans = cur = ListNode(None)  # return
        flag = 0
        while l1 or l2 or flag:
            if not l1 and not l2:
                suml = flag
            elif not l1:
                suml = l2.val + flag
            elif not l2:
                suml = l1.val + flag
            else:
                suml = l1.val + l2.val + flag
            if suml >= 10:
                flag = 1
                tmp = ListNode(suml - 10)
            else:
                flag = 0
                tmp = ListNode(suml)
            cur.next = tmp
            cur = cur.next
            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next
        return ans.next

大佬们的写法

# 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:
        dummy = p = ListNode(None) #保存头结点,返回结果
        s = 0 #每一步的求和暂存变量
        while l1 or l2 or s:           #循环条件:l1 或者l2(没有遍历完成),s(进位)不为0
            s += (l1.val if l1 else 0) + (l2.val if l2 else 0)           #这其实是好多代码,我自己写了好多行,但是作者这样写非常简洁,赞
            p.next = ListNode(s % 10)             #构建新的list存储结果,其实用较长的加数链表存也可以,%10:求个位
            p = p.next                        
            s //= 10                                         #求进位
            l1 = l1.next if l1 else None           
            l2 = l2.next if l2 else None
        return dummy.next
©️2020 CSDN 皮肤主题: 像素格子 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值