用栈来消除递归,求得,其思想就是先循环n次,将n个f存入栈中,然后再循环n次(可以用栈非空来判断)依次拿出n个f,每次在所得上乘以f
我们可以用以下方式实现:
/* 用栈模拟递归过程求阶乘 */
# include <stdio.h>
# include <iostream>
# include <stdlib.h>
using namespace std;
#define MAXSIZE 20
typedef struct {
int* data;
int* top;
int maxsize;
}Stack;
void stack_init(Stack &S)
{
S.data = (int*)malloc(sizeof(int)*MAXSIZE);
if (!S.data) exit(0);
S.top = S.data;
S.maxsize = MAXSIZE;
}
void stack_push(Stack &S,int e)
{
*S.top++ = e;
}
void stack_pop(Stack &S,int &f)
{
f = *--(S.top);
}
bool stack_empty(Stack S)
{
if (S.top == S.data) return true;
return false;
}
void fact(int &f,int n)
/* 求f^n */
{
Stack S;
stack_init(S);
while (n){//将栈里面填入n个f
stack_push(S,f);
n--;
}
f=1;
while (!stack_empty(S)){
stack_pop(S,n);//这块用n也就是节省了一个参数
f*=n;
}
}
int main()
{
int f,n,ans;
cout << "I can count f^n, please enter the number f and n" << endl;
cin >> f >> n;
fact(f,n);
cout << "the answer is " << f << endl;
return 0;
}