/********************************引入头文件**************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
/**********************************定义*******************************************************/
#define OK 0
#define ERROR -1
#define OVERFLOW -2
#define DEFSIZE 10
#define INCREAMSIZE 10
typedef int Status;
typedef int ElemType;
typedef struct{
ElemType *base;
ElemType *top;
int stackSize;
int realSize;
}SqStack;
/*********************************stack操作方法**************************************************/
Status InitStack(SqStack &sqstack)
{
sqstack.base = (ElemType*)malloc(DEFSIZE*sizeof(ElemType));
if(!sqstack.base) exit(OVERFLOW);
sqstack.top = sqstack.base;
sqstack.stackSize = DEFSIZE;
sqstack.realSize = 0;
return OK;
}
Status Push(SqStack &sqstack,ElemType &e)
{
if(sqstack.top-sqstack.base>=sqstack.stackSize)
{
sqstack.base = (ElemType*)realloc(sqstack.base,(sqstack.stackSize+INCREAMSIZE)*sizeof(ElemType));
if(!sqstack.base) exit(OVERFLOW);
sqstack.top = sqstack.base + sqstack.stackSize;
sqstack.stackSize = sqstack.stackSize + INCREAMSIZE;
}
*sqstack.top++ = e;
sqstack.realSize++;
return OK;
}
Status Pop(SqStack &sqstack,ElemType &e)
{
if(sqstack.base==sqstack.top)
{
exit(ERROR);
}
e = *--sqstack.top;
sqstack.realSize--;
return OK;
}
Status GetTop(SqStack &sqstack,ElemType &e)
{
if(sqstack.base==sqstack.top)
{
exit(ERROR);
}
e = *(sqstack.top-1);
return OK;
}
bool IsEmpty(SqStack &sqstack)
{
if(sqstack.realSize>0)
return false;
else
return true;
}
Status DestroyStack(SqStack &sqstack)
{
sqstack.top = sqstack.base;
free(sqstack.base);
sqstack.realSize = 0;
sqstack.stackSize = DEFSIZE;
return OK;
}
int StackLength(SqStack &sqstack)
{
return sqstack.realSize;
}
/*******************************主函数************************************************/
int main(int argc, char *argv[])
{
SqStack sqstack;
int N = 0;
int temp = 0;
/****初始化栈***/
InitStack(sqstack);
printf("初始化时,堆的大小为:%d\n",sqstack.stackSize);
/**根据输入来填充栈**/
printf("请入你想要输入几个数据进栈:");
scanf("%d",&N) ;
while(N--)
{
scanf("%d",&temp);
Push(sqstack,temp);
printf("进栈的大小为:%d\t",temp);
printf("压栈后,栈的大小为:%d,%d\n",temp,sqstack.stackSize);
}
/**得到栈顶元素**/
GetTop(sqstack,temp);
printf("得到栈顶元素为:%d",temp);
/**将栈的元素逐一出栈**/
DestroyStack(sqstack);
printf("销毁栈完成!!\n");
scanf("%d",&temp);
return 0;
}