#include "stdafx.h"
#include<cstdio>
#include<cstdlib>
#define OK 1
#define TRUE 1
#define ERROR 0
#define FALSE 0
#define overflow -2
#define STACK_INTT_SIZE 100
#define STACK_INIT_INCREMENT 20
#define Status int
#define ElemType int
typedef struct
{
ElemType *base,*top;
int stackSize;
}SqStack;
/* 栈的操作
Status InitStatck(SqStack &s) 初始化栈
Status DestoryStatck(SqStack &s) 销毁栈
Status ClearStack(SqStack &s) 清除栈
bool StackEmpty(SqStack s) 栈是否为空
int StackLength(SqStack s) 栈的长度
Status GetTop(SqStack s,SElemType &e) 得到栈顶
Status Push(SqStack &s,SElemType e) 压栈
Status Pop(SqStack &s,SElemType &e) 出栈
void DisplayStack(SqStack s); 显示栈内的元素
*/
Status InitStatck(SqStack &s)
{
s.base=(ElemType*)malloc(STACK_INTT_SIZE*(sizeof(ElemType)));
if(!s.base)
return ERROR;
else
s.top=s.base;
s.stackSize=STACK_INTT_SIZE;
}
Status DestoryStatck(SqStack &s)
{
s.top=s.base;
free(s.base);
s.base=NULL;
s.top=NULL;
return OK;
}
bool StackEmpty(SqStack s)
{
if(s.base==s.top)
return TRUE;
else
return FALSE;
}
int StackLength(SqStack s)
{
if(s.base=s.top)
return ERROR;
else
return (s.top-s.base);
}
Status GetTop(SqStack s,ElemType &e)
{
if(StackEmpty(s))
{
printf("This stack is empty.");
return ERROR;
}
else
{
s.top--;
e=*s.top;
return OK;
}
}
Status Push(SqStack &s,ElemType e)
{
if(StackLength(s)==STACK_INTT_SIZE)
{
ElemType*temp=(ElemType*)realloc(s.base,(STACK_INTT_SIZE+STACK_INIT_INCREMENT)*(sizeof(ElemType)));
if(!temp)
return ERROR;
s.base=temp;
s.top=s.base+STACK_INTT_SIZE;
s.stackSize=STACK_INTT_SIZE+STACK_INIT_INCREMENT;
*(s.top++)=e;
return OK;
}
else
{
*s.top=e;
s.top++;
return OK;
}
}
Status Pop(SqStack &s,ElemType &e)
{
if(StackEmpty(s))
{
printf("This stack is empty.");
return ERROR;
}
else
{
e=*(--s.top);
return OK;
}
}
Status ClearStack(SqStack &s)
{
s.top=s.base;
s.stackSize=0;
return OK;
}
void DisplayStack(SqStack s)
{
if(StackEmpty(s))
exit(-1);
while(s.top!=s.base)
printf("%d\n",*(--s.top));
}
int _tmain(int argc, _TCHAR* argv[])
{
SqStack statck;
InitStatck(statck);
for(int i=0;i<5;i++)
{
if(Push(statck,i))
printf("%d is push in this statck success!\n",i);
else
printf("/n/thappen a error\n\t");
}
DisplayStack(statck);//显示栈内的元素
int tem;
printf("now i will print this top of statck !\n");
GetTop(statck,tem);
printf("%d is top of this statck\n",tem);
DestoryStatck(statck);
system("pause");
return 0;
}