文章参考过网上的内容,如果侵权,请联系
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 30
#define STACKINCREMENT 5
#define ERROR 0
#define OK 1
#define OVERLOAD -2
typedef struct{
int *base;
int *top;
int stacksize;
}SqStack;
int InitStack(SqStack &S){
//构造一个空栈S
S.base=(int *)malloc(STACK_INIT_SIZE*sizeof(int));
if(!S.base)
{
exit(OVERLOAD); //存储分配失败
}
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}//InitStack
int GetTop(SqStack S,int &e)
{ //若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR
if(S.top==S.base) return ERROR;
e=*(S.top-1);
printf("栈顶元素为:%d\n",e);
return OK;
}//GetTop
int Push(SqStack &S,int e)
{ //插入元素e为新的栈顶元素
if(S.top-S.base>=S.stacksize){//栈满,追加存储空间
S.base=(int *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(int));
if(!S.base) exit(OVERLOAD); //存储分配失败
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;//先赋值后移动
return OK;
}//Push
int Pop(SqStack &S,int &e)
{ //若栈不空,则删除S的栈顶元素.用e返回其值,并返回OK;否则返回ERROR
if(S.top==S.base) return ERROR;
e=*--S.top;//先移动后赋值
return e;
return OK;
}//Pop
void ClearStack(SqStack &S)
{ //清空栈
int e;
while(S.top!=S.base)
{
Pop(S,e); S.top--;
}
printf("清空完成\n");
}
void StackTraverse(SqStack S)
{ //遍历栈
int *p=S.base;
if(p) p++;
else printf("遍历失败\n");
printf("遍历成功\n");
}
void out(SqStack &S)
{
int *p=S.top;
while(p>S.base){printf("%d",*(p-1)); p--;}
printf("\n");
}
int main()
{
SqStack S;
InitStack(S);
int t,e;
printf("输入栈元素个数:\n");
scanf("%d",&t);
printf("输入%d个元素:\n",t);
while(t--)
{
scanf("%d",&e);
Push(S,e);
}
printf("插入栈顶元素:\n输入元素:\n");
scanf("%d",&e);
Push(S,e);
out(S);
printf("删除栈顶元素:\n");
printf("被删除元素为:%d\n",Pop(S,e));
printf("取栈顶元素:\n");
GetTop(S,e);
printf("遍历栈:\n");
StackTraverse(S);
printf("置空栈:\n");
ClearStack(S);
}