给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例1:
输入:l1 = [7,2,4,3], l2 = [5,6,4] 输出:[7,8,0,7]
示例2:
输入:l1 = [2,4,3], l2 = [5,6,4] 输出:[8,0,7]
示例3:
输入:l1 = [0], l2 = [0] 输出:[0]
class Solution:
def reverse_list(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
while head:
next_node = head.next
head.next = prev
prev = head
head = next_node
return prev
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
# Step 1: Reverse both lists
l1 = self.reverse_list(l1)
l2 = self.reverse_list(l2)
dummy = ListNode(0)
current = dummy
carry = 0
# Step 2: Add the numbers
while l1 or l2 or carry:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
total = val1 + val2 + carry
carry = total // 10
current.next = ListNode(total % 10)
current = current.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
# Step 3: Reverse the result list
return self.reverse_list(dummy.next)
#