题目 You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zeros, except the number 0 itself.
Example 1:
1 2 3 Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807.
Example 2:
1 2 Input: l1 = [0], l2 = [0] Output: [0]
Example 3:
1 2 Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1]
题目大意 给定两个逆序存储数字各位的非空链表(如 2->4->3 表示 342),将这两个数相加并以链表形式返回结果。假设两数除 0 外无前导零,需处理进位情况。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: cur = dummy = ListNode() # 哨兵节点 carry = 0 # 进位 while l1 or l2 or carry: # 有一个不是空节点,或者还有进位,就继续迭代 if l1: carry += l1.val # 节点值和进位加在一起 l1 = l1.next # 下一个节点 if l2: carry += l2.val # 节点值和进位加在一起 l2 = l2.next # 下一个节点 cur.next = ListNode(carry % 10) # 每个节点保存一个数位 carry //= 10 # 新的进位 cur = cur.next # 下一个节点 return dummy.next # 哨兵节点的下一个节点就是头节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode(0) node = dummy # node 一直会变化(前进) carrier = 0 # 进位 while l1 or l2 or carrier: sum = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carrier node.next = ListNode(sum % 10) node = node.next carrier = sum // 10 if l1: l1 = l1.next if l2: l2 = l2.next return dummy.next