mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-06 14:27:26 +08:00
feat(csharp): add forLoopRecur and new HashMapOpenAddressing (#783)
This commit is contained in:
@ -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);
|
||||
|
||||
|
Reference in New Issue
Block a user