转自:http://www.cnblogs.com/kwklover/archive/2006/04/08/369923.html
问:为什么要递归转非递归?
答:因为每一次的递归调用都需要压栈占用内存,效率不高。
一般的递归方法(以求阶乘为例):
unsigned long long Recursive(unsigned long long n) { if (n > 1) { return n * Recursive(n - 1); } else if (n == 1) { return 1; } }
递归转非递归的两种方法:
循环非递归法:
unsigned long long NoRecursiveByLoop(unsigned long long n) { int k = 1; int t = 1; while (k <= n) { t *= k; k++; } return t; }
自定义堆栈非递归法:
unsigned long long NoRecursiveByStack(unsigned long long n) { Stack<int> s = new Stack<int>(); int t = 1; int temp; s.Push(n); while ((temp = s.Peek()) != 1) { t *= s.Peek(); s.Pop(); s.Push(temp - 1); } return t; }