题目:
题解:
class Solution:def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:if head is None or head.next is None:return headnew_head = self.reverseList(head.next)head.next.next = head # 把下一个节点指向自己head.next = None # 断开指向下一个节点的连接,保证最终链表的末尾节点的 next 是空节点return new_head# l1 和 l2 为当前遍历的节点,carry 为进位def addTwo(self, l1: Optional[ListNode], l2: Optional[ListNode], carry=0) -> Optional[ListNode]:if l1 is None and l2 is None: # 递归边界:l1 和 l2 都是空节点return ListNode(carry) if carry else None # 如果进位了,就额外创建一个节点if l1 is None: # 如果 l1 是空的,那么此时 l2 一定不是空节点l1, l2 = l2, l1 # 交换 l1 与 l2,保证 l1 非空,从而简化代码carry += l1.val + (l2.val if l2 else 0) # 节点值和进位加在一起l1.val = carry % 10 # 每个节点保存一个数位l1.next = self.addTwo(l1.next, l2.next if l2 else None, carry // 10) # 进位return l1def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:l1 = self.reverseList(l1)l2 = self.reverseList(l2) # l1 和 l2 反转后,就变成【2. 两数相加】了l3 = self.addTwo(l1, l2)return self.reverseList(l3)