feat(dart): add forLoopRecur and update HashMapOpenAddressing (#802)

* feat(dart): add forLoopRecur

* feat(dart): update HashMapOpenAddressing
This commit is contained in:
liuyuxin
2023-09-26 11:04:13 +08:00
committed by GitHub
parent e567d08348
commit e3366363b6
3 changed files with 82 additions and 65 deletions

View File

@ -14,6 +14,25 @@ int recur(int n) {
return n + res;
}
/* 使用迭代模拟递归 */
int forLoopRecur(int n) {
// 使用一个显式的栈来模拟系统调用栈
List<int> stack = [];
int res = 0;
// 递:递归调用
for (int i = n; i > 0; i--) {
// 通过“入栈操作”模拟“递”
stack.add(i);
}
// 归:返回结果
while (!stack.isEmpty) {
// 通过“出栈操作”模拟“归”
res += stack.removeLast();
}
// res = 1+2+3+...+n
return res;
}
/* 尾递归 */
int tailRecur(int n, int res) {
// 终止条件
@ -43,6 +62,9 @@ void main() {
res = tailRecur(n, 0);
print("\n尾递归函数的求和结果 res = $res");
res = forLoopRecur(n);
print("\n使用迭代模拟递归求和结果 res = $res");
res = fib(n);
print("\n斐波那契数列的第 $n 项为 $res");
}