feat(csharp): add forLoopRecur and new HashMapOpenAddressing (#783)

This commit is contained in:
hpstory
2023-09-24 03:15:23 +08:00
committed by GitHub
parent 2f727d895d
commit 29c5ff4a8f
2 changed files with 82 additions and 56 deletions

View File

@ -18,6 +18,25 @@ public class recursion {
return n + res;
}
/* 使用迭代模拟递归 */
public int forLoopRecur(int n) {
// 使用一个显式的栈来模拟系统调用栈
Stack<int> stack = new Stack<int>();
int res = 0;
// 递:递归调用
for (int i = n; i > 0; i--) {
// 通过“入栈操作”模拟“递”
stack.Push(i);
}
// 归:返回结果
while (stack.Count > 0) {
// 通过“出栈操作”模拟“归”
res += stack.Pop();
}
// res = 1+2+3+...+n
return res;
}
/* 尾递归 */
public int tailRecur(int n, int res) {
// 终止条件
@ -47,6 +66,9 @@ public class recursion {
res = recur(n);
Console.WriteLine("\n递归函数的求和结果 res = " + res);
res = forLoopRecur(n);
Console.WriteLine("\n使用迭代模拟递归求和结果 res = " + res);
res = tailRecur(n, 0);
Console.WriteLine("\n尾递归函数的求和结果 res = " + res);