/*
编译器:Dev-c++ 5.4.0
文件名:stack.cpp
代码版本号:1.0
时间:2015-10-10 20:08:54
*/
#include <stdio.h>
#include <stdlib.h>
#define ERROR 0
#define OK 1
#define FALSE 0
#define TRUE 1
#define OVERFLOW -2
#define INIT_STACK_SIZE 100
#define STACK_INCREMENT 10
typedef int sElemType;
typedef int Status;
typedef struct {
sElemType *base;
sElemType *top;
int stackSize;
}sqStack;
/*初始化INIT_STACK_SIZE大小的空栈*/
Status initStack(sqStack *s){
s->stackSize=INIT_STACK_SIZE;
s->base=s->top=(sElemType *)malloc(INIT_STACK_SIZE*sizeof(sElemType));
return OK;
}
/*销毁栈*/
Status destroyStack(sqStack *s){
free(s->base);
s->base=s->top=NULL;
s->stackSize=;
return OK;
}
/*把S栈置为空栈*/
Status clearStack(sqStack *s){
s->base=s->top;
return OK;
}
/*判断栈是否为空栈*/
bool emptyStack(sqStack *s){
if(s->base==s->top)
return TRUE;
else
return FALSE;
}
int stackLength(sqStack *s){
return s->top-s->base;
}
/*入栈*/
Status push(sqStack *s,sElemType e){
if(s->top-s->base>=(s->stackSize-))
{
s->base=(sElemType *)realloc(s->base,(INIT_STACK_SIZE+STACK_INCREMENT)*sizeof(sElemType));
s->top=s->base+s->stackSize-;
s->stackSize+=STACK_INCREMENT;
}
*(s->top)=e;
s->top++;
return OK;
}
/*出栈*/
Status pop(sqStack *s,sElemType *e){
if(s->base==s->top)
return ERROR;
*e=*--s->top;
return OK;
}
/*得到栈顶元素*/
Status getTop(sqStack s,sElemType *e){
if(s.base==s.top)
return ERROR;
*e=*(s.top-);
return OK;
}
int visit(sElemType c){
printf("%d ",c);
return ;
}
/*遍历栈*/
Status stackTraverse(sqStack *s,int (*visit)(sElemType)){
for(sElemType *i=s->base;i<s->top;i++){
visit(*i);
}
return OK;
}
int main(){
sqStack S;
initStack(&S);
printf("\n请输入您想入栈数据的个数:");
int m;
sElemType e;
scanf("%d",&m);
for(int i=;i<=m;i++){
printf("\n请输入第%d个数据",i);
scanf("%d",&e);
push(&S,e);
}
stackTraverse(&S,visit);
printf("\n弹出一个数据后");
pop(&S,&e);
stackTraverse(&S,visit);
printf("\n得到的栈顶元素:");
getTop(S,&e);
printf("%d\n",e);
printf("栈的长度为%d",stackLength(&S));
system("pause");
return ;
}