栈的简单实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct SqStack{
int *base;
int top;
int stacksize;
}SqStack;
void InitStack(SqStack &S)
{//构造一个空的栈
S.base=(int *)malloc(STACK_INIT_SIZE*sizeof(SqStack));
if(!S.base)
exit(0);
S.top=0;
S.stacksize=STACK_INIT_SIZE;
}
int Push(SqStack &S,int e)
{//元素进栈
if(S.top>=S.stacksize-1)
{
S.base=(int *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SqStack));
}
S.base[S.top]=e;
S.top++;
if(S.base[S.top-1]==e)
return 1;
else
return 0;
}
int pop(SqStack &S,int &e)
{//元素出栈
if(S.top >= 1)
{
S.top--;
e=S.base[S.top];
return 1;
}
return 0;
}
int main()
{
SqStack S;
int e,n;
InitStack(S);
printf("请输入你要压入的数据个数n\n");
scanf("%d",&n);
printf("请依次输入%d个元素,以空格隔开,回车结束\n",n);
for(int i=0;i<n;i++)
{
scanf("%d",&e);
if(Push(S,e))
printf("第%d个元素插入成功\n",i+1);
else
printf("第%d个元素插入失败\n",i+1);
}
n=S.top;
for(int i=0;i<n;i++)
{
pop(S,e);
printf("%d ",e);
}
printf("\n");
return 0;
}