用栈的方式实现递归调用(以n的阶乘为例)

来源:互联网 发布:姚明nba前几场比赛数据 编辑:程序博客网 时间:2024/05/20 23:56
#include<stdio.h>  
#include<stdlib.h>  
#define STACK_INIT_SIZE 100 
#define STACK_INCREMENT 10   
#define ERROR 0  
#define right  1  
typedef int SType;
typedef int Status;
typedef struct Stack
{
      SType *top; 
SType *base;
int stacksize;
}Stack; 


// 构造空栈Stack
Status Initstack(Stack &S)

if (!(S.base = (SType *)malloc(STACK_INIT_SIZE * sizeof (SType))))
return ERROR; // 存储分配失败  
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;  
return right;
}


/* 输入栈元素 */
Status Push(Stack &S, SType e){
if (S.top - S.base >= S.stacksize) 
{

S.base = (SType *)realloc(S.base, //原栈底指针  
(S.stacksize + STACK_INCREMENT) * sizeof (SType));
if (!S.base)
return ERROR; // 存储分配失败
S.top = S.base + S.stacksize;
S.stacksize += STACK_INCREMENT;
}
*S.top++ = e;
//先把e压入栈顶,S.top再增1指向栈顶元素e的下一个位置  
return right;
}


/* 栈是否是空的 */
Status StackEmpty(Stack S)
{


if (S.top == S.base)
return right;
else
return ERROR;
}


/* 删除栈顶元素*/
Status Pop(Stack &S, SType &e)
{
if (S.top == S.base) 
return ERROR;
e = *--S.top; 
return right;
}




void fact(int N){
int sum = 1;
Stack S;
SType e;
Initstack(S);
while (N){
Push(S, N);
N--;
}
while (!StackEmpty(S))
{
sum *= *(S.top - 1);
Pop(S, e);
}
printf("result is %d\n", sum);
}
void main()
{
int n;
printf("请输入n的阶数\n");
scanf_s("%d", &n);
fact(n);
}
原创粉丝点击