目录
前言
将一个简单的递归函数用栈改写成非递归形式
提示:以下是本篇文章正文内容,下面案例可供参考
一、递归函数
void test(int &sum)
{
int x;
cin>>x;
if(x == 0) sum = 0;
else{
test(sum);
sum += x;
}
cout<<sum;
}
函数的功能即倒序用户的输入之和,例如输入1 2 3,输出即为3 5 6
二、非递归版本(栈)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
typedef int ElemType;
typedef struct
{
ElemType* base;//栈底
ElemType* top; //栈顶
int stackSize; //栈的大小
}sqStack;
void InitStack(sqStack* s)
{ //建立一个栈
s->base = (ElemType*)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if (!s->base)
{
exit(0);
}
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
}
void Push(sqStack* s, ElemType e)
{ //压栈
if (s->top - s->base >= s->stackSize)
{ //若栈满了,就动态扩容
s->base = (ElemType*)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(ElemType));
if (!s->base)
{
exit(0);
}
}
*s->top = e;
s->top++;
}
void Pop(sqStack* s, ElemType* e)
{ //弹栈
if (s->top == s->base)
{
return;
}
*e = *--(s->top);
}
int StackLen(sqStack s)
{ //返回栈的大小
return (s.top - s.base);
}
int main()
{
ElemType c;
sqStack s;
int len, sum = 0;
InitStack(&s);
printf("请输入数字,输入0表示结束:");
scanf("%d", &c);
while (c != 0)
{
Push(&s, c);
scanf("%d", &c);
}
len = StackLen(s);//表示栈当前的大小
printf("0 ");
for (int i = 0; i < len; i++)
{
Pop(&s, &c);
sum += c;
printf("%d ", sum);
}
return 0;
}
还没学C++,用C语言版本的写了下