2. 两数相加

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

代码:

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution:
  7. def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
  8. ans = ListNode(0)
  9. aa = ans
  10. carry = 0
  11. while (l1 or l2) :
  12. x = l1.val if l1 else 0
  13. y = l2.val if l2 else 0
  14. sum = carry + x + y
  15. carry = sum // 10
  16. aa.next = ListNode(sum % 10)
  17. aa = aa.next
  18. if l1 : l1 = l1.next
  19. if l2 : l2 = l2.next
  20. if carry > 0:
  21. aa.next = ListNode(1)
  22. return ans.next