leetcode445. 两数相加 II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36811967/article/details/84778763

比之前那个两数相加增加了点难度:
https://leetcode-cn.com/problems/add-two-numbers-ii

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

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        list1, list2 = [], []
        while l1:
            list1.append(l1.val)
            l1 = l1.next
        while l2:
            list2.append(l2.val)
            l2 = l2.next
        res = ListNode(0)
        flag = 0
        cur = res
        while list1 or list2:
            x, y = 0, 0
            if list1:
                x = list1.pop()
            if list2:
                y = list2.pop()
            sum_xy = flag + x + y
            flag = sum_xy // 10
            tmp = ListNode(sum_xy % 10)
            tmp.next = cur.next
            cur.next = tmp
        if flag:
            tmp = ListNode(flag)
            tmp.next = cur.next
            cur.next = tmp
        return res.next

猜你喜欢

转载自blog.csdn.net/sinat_36811967/article/details/84778763