当你看到这个时,你会想起你敲过多少遍:
#include <stdio.h>
#include <stdlib.h>
#define ElemType int
#define Status int
#define INIT_SIZE 10 //初始化长度
#define INCRE_SIZE 10 //增量
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef struct{
ElemType *top; //栈顶指针
ElemType *base;//栈底指针
int stackSize;
}SqStack;
//初始化栈
Status InitStack(SqStack &S){
S.base = (ElemType*)malloc(sizeof(ElemType)*INIT_SIZE);
if(!S.base){
exit(OVERFLOW);
}
S.top = S.base;//栈顶栈底同时指向底部
S.stackSize = INIT_SIZE;
return OK;
}
//取得顶部元素
Status GetTop(SqStack S,ElemType &e){
if(S.top == S.base){ //栈为空,没有元素
return ERROR;
}
e = *--S.top;//栈顶先减后取值
return OK;
}
//进栈
Status Push(SqStack &S,ElemType e){
if(S.top - S.base >= S.stackSize){ //空间已用完
S.base = (ElemType*)realloc(S.base,sizeof(ElemType)*INCRE_SIZE);//注意这里是realloc重新分配
if(!S.base){
exit(OVERFLOW);
}
S.top = S.base + S.stackSize;//栈顶重新指向栈顶
S.stackSize += INCRE_SIZE;
}
*S.top++ = e;//否则直接赋值到栈顶后栈顶指针往后移
return OK;
}
//出栈
Status Pop(SqStack &S,ElemType &e){
if(S.top == S.base){
return ERROR;
}
e = *--S.top;//先减后取值
return OK;
}
//判断栈空
Status IsStackEmpty(SqStack S){
if(S.base == S.top){
return OK;
}else{
return ERROR;
}
}
//判断栈是否满
Status IsStackFull(SqStack S){
if(S.top - S.base == S.stackSize){
return OK;
}else{
return ERROR;
}
}
//获得栈的长度
int GetStackLength(SqStack S){
return S.top - S.base;
}
//销毁栈
void DestroyStack(SqStack &S){
S.base = S.top = NULL;
}
//打印栈中元素
void PrintStack(SqStack S){
ElemType e;
SqStack ST;//过渡的栈
InitStack(ST);
while(S.top != S.base){//将S中的元素逆序
Pop(S,e);
Push(ST,e);
}
while(ST.top != ST.base){
Pop(ST,e);
printf("%d ",e);
}
DestroyStack(ST);
printf("\n");
}
int main(){
//测试
SqStack S;
InitStack(S);
printf("初始化栈成功...\n");
ElemType x;
printf("输入5个数:");
int i = 5;
while(i-->0){
scanf("%d",&x);
Push(S,x);
}
printf("进栈成功\n");
printf("栈中元素为:");
PrintStack(S);
Pop(S,x);
printf("Pop弹出的元素为:%d\n",x);
printf("栈中元素为:");
PrintStack(S);
GetTop(S,x);
printf("GetTop的元素为:%d\n",x);
printf("栈中元素为:");
PrintStack(S);
printf("栈的长度为:%d\n",GetStackLength(S));
DestroyStack(S);
printf("销毁栈成功\n");
return 0;
}