隋代敦煌莫高窟壁画:求数据结构栈简单程序,送300积分

来源:百度文库 编辑:查人人中国名人网 时间:2024/05/08 00:34:31
求C语言完整程序,题目:给定一个栈S,编写一个函数算法求此栈的元素个数(要求分别使用递归和非递归实现)
一定要是可运行的哦

#include <stdio.h>
#define SZ 1000
typedef struct
{
int data[SZ];
int top;
int base;
}Stack;
void init(Stack *s)/*初始化栈*/
{s->base=0;
s->top=0;
}
void push(Stack *s,int a)/*入栈*/
{
s->data[s->top]=a;
s->top=s->top+1;
}
int pop(Stack* s)/*出栈*/
{
s->top=s->top-1;
return s->data[s->top];
}
int getSize1(Stack s) /*非递归算法获取栈元素个数*/
{
int size=0;
while(s.top!=s.base) {size++;pop(&s);}
return size;
}
int getSize2(Stack s) /*递归算法获取栈元素个数*/
{
int size;
if(s.top==0) return 0;
else
{pop(&s);
size=1+getSize2(s);
}
return size;
}
main()
{
int t;
Stack S;
init(&S);
push(&S,1);
push(&S,2);
push(&S,3);
push(&S,4);

printf("%d",getSize1(S));
printf("%d",getSize2(S));
}