尾递归与尾调用优化深度解析:从栈帧到Python的替代方案
一、直观对比:普通递归 vs 尾递归1.1 普通递归:阶乘1234def factorial(n): if n == 0: return 1 return n * factorial(n - 1) # 递归调用后还要做乘法! 关键问题:n * factorial(n - 1) 中,递归调用 factorial(n - 1) 返回后,还要乘以 n。这意味着当前函数的栈帧不能被销毁——它必须等递归返回后继续计算。 1.2 尾递归:阶乘1234def factorial_tail(n, acc=1): if n == 0: return acc return factorial_tail(n - 1, acc * n) # 递归调用是最后一步! 关键区别:factorial_tail(n - 1, acc * n)...
Leetcode 0206. Reverse Linked List
206. Reverse Linked ListGiven the head of a singly linked list, reverse the list, and return the reversed list. Example 1: 12Input: head = [1,2,3,4,5]Output: [5,4,3,2,1] Example 2: 12Input: head = [1,2]Output: [2,1] Example 3: 12Input: head = []Output: [] Constraints: The number of nodes in the list is the range [0, 5000]. -5000 <= Node.val <= 5000 解法 1:迭代解法123456789101112131415161718192021222324252627/** * Definition for singly-linked list. * struct ListNode { * int...
Leetcode 0002. Add Two Numbers
2. Add Two Numbers题目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: 123Input: l1 = [2,4,3], l2 = [5,6,4]Output: [7,0,8]Explanation: 342 + 465 = 807. Example 2: 12Input: l1 = [0], l2 = [0]Output: [0] Example...
Leetcode 0002. Add Two Numbers
2. Add Two Numbers题目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: 123Input: l1 = [2,4,3], l2 = [5,6,4]Output: [7,0,8]Explanation: 342 + 465 = 807. Example 2: 12Input: l1 = [0], l2 = [0]Output: [0] Example...

