#include<stdio.h>#include<malloc.h>#defineERROR0#defineOK1#defineTrue1#defineFalse0#defineSTACK_INT_SIZE10/*存储空间初始分配量*/#defineSTACKINCREMENT5/*存储空间分配增量*/typedefint ElemType;/*定义元素的类型*/typedefint Status;/*定义元素的类型*/typedefstruct{
ElemType *base;
ElemType *top;int stacksize;/*当前已分配的存储空间*/}SqStack;
Status InitStack(SqStack &S);/*构造空栈*/
Status push(SqStack &S,ElemType e);/*入栈*/
Status Pop(SqStack &S,ElemType &e);/*出栈*/
Status GetTop(SqStack S, ElemType &e);/*取顺序栈栈顶元素*/
Status StackEmpty(SqStack S);/*判断顺序栈是否为空*/intStackLength( SqStack S );/*求顺序栈的长度*/
Status CreateStack(SqStack &S);/*创建栈*/voidPrintStack(SqStack &S);/*出栈并输出栈中元素*/
Status DestroyStack( SqStack &S );/*销毁栈*/
Status InitStack(SqStack &S){/*构造空栈*/
S.base=(ElemType *)malloc(STACK_INT_SIZE *sizeof(ElemType));if(!S.base)return ERROR;
S.top=S.base;
S.stacksize=STACK_INT_SIZE;return OK;}/*InitStack*/
Status Push(SqStack &S,ElemType e)/*入栈*/{if(S.top-S.base>=S.stacksize){
S.base =(ElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(ElemType));if(!S.base)return ERROR;
S.top=S.base+S.stacksize ;
S.stacksize += STACKINCREMENT;}*S.top++=e;return OK;}/*Push*/
Status Pop(SqStack &S,ElemType &e)/*出栈*/{if(S.top == S.base )return ERROR;
e=*--S.top;return OK;}/*Pop*/
Status GetTop(SqStack S, ElemType &e)/*取顺序栈栈顶元素*/{if(S.top ==S.base )return ERROR;
e=*(S.top-1);return OK;}/*GetTop*/
Status StackEmpty(SqStack S)/*判断顺序栈是否为空*/{if(S.top ==S.base )return ERROR;elsereturn OK;}/*StackEmpty*/intStackLength( SqStack S )/*求顺序栈的长度*/{int i;if(S.top ==S.base )return ERROR;
i=S.top-S.base;return OK;}/*StackLength*/
Status CreateStack(SqStack &S){int e;if(InitStack(S))printf("Init Success!\n");else{printf("Init Fail!\n");return ERROR;}printf("input data:(Terminated by inputing a character)\n");while(scanf("%d",&e))Push(S,e);return OK;}/*CreateStack*/voidPrintStack(SqStack &S){
ElemType e;while(Pop(S,e))printf("%3d",e);printf("\n");}/*Pop_and_Print*/
Status DestroyStack(SqStack &S)/*销毁栈*/{if( S.base ){free(S.base);
S.stacksize =0;
S.base = S.top =NULL;}return OK;}intmain(){
SqStack ss;
ElemType e;printf("\ncreate Stack\n");CreateStack(ss);Push(ss,e);GetTop(ss,e);printf("\nData on the top of the Stack is %d\n",e);printf("\n");if(StackEmpty(ss))printf("\nthe Stack is empty.\n");elseprintf("\nthe Stack is not empty.\n");printf("\n");printf("\nThere are %d datas in the Stack \n",StackLength(ss));printf("\n");printf("\nPop&Print\n");PrintStack(ss);if(StackEmpty(ss))printf("\nthe Stack is empty.\n");elseprintf("\nthe Stack is not empty.\n");printf("\n");DestroyStack(ss);return0;}