leetcode445. 两数相加 II

【leetcode445. 两数相加 II】比之前那个两数相加增加了点难度:
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 = Noneclass 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

    推荐阅读