#include<stdio.h>#include<stdlib.h>#define TRUE 1#define FALSE 0#define OK 1#define ERROR 0#define INFEASIBLE -1#define OVERFLOW -2typedefint Status;typedefint SElemType;#define STACK_INIT_SIZE 100#define STACKINCREMENT 10typedefstruct{
SElemType* base;
SElemType* top;int stacksize;}SqStack;
Status InitStack(SqStack& S);
Status DestroyStack(SqStack& S);
Status ClearStack(SqStack& S);
Status StackEmpty(SqStack& S);intStackLength(SqStack S);
Status GetTop(SqStack S, SElemType& e);
Status Push(SqStack& S, SElemType e);
Status Pop(SqStack& S, SElemType& e);voidprint_SqStack(SqStack S);intmain(){
SqStack S;InitStack(S);
SElemType e;Push(S,3);Push(S,2);Push(S,4);print_SqStack(S);Pop(S, e);print_SqStack(S);system("pause");return0;}
Status InitStack(SqStack& S){
S.base =(SElemType*)malloc(STACK_INIT_SIZE *sizeof(SElemType));if(!S.base)exit(OVERFLOW);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;return OK;}
Status DestroyStack(SqStack& S){free(&S);return OK;}
Status ClearStack(SqStack& S){
S.top = S.base;return OK;}
Status StackEmpty(SqStack& S){if(S.top == S.base)return TRUE;return FALSE;}intStackLength(SqStack S){if(S.base > S.top)return INFEASIBLE;return(S.top - S.base);}
Status GetTop(SqStack S, SElemType& e){if(S.top == S.base)return ERROR;
e =*(S.top -1);return OK;}
Status Push(SqStack& S, SElemType e){if(S.top - S.base >= S.stacksize){
S.base =(SElemType*)realloc(S.base,(S.stacksize + STACKINCREMENT)*sizeof(SElemType));if(!S.base)exit(OVERFLOW);
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;}*S.top++= e;}
Status Pop(SqStack& S, SElemType& e){if(S.top == S.base)return ERROR;
e =*--S.top;return OK;}voidprint_SqStack(SqStack S){
SElemType* p;
p = S.base;printf("S(length:%d):",StackLength(S));while(p < S.top){printf("%d ",*p);
p++;}printf("\n");}
3.2 栈的应用举例
3.2.1 数制转换
利用栈的后入先出结构
对于输入的任意一个非负十进制整数,打印输出与其等值的八进制数
voidconversion(){//对于输入的任意一个非负十进制整数,打印输出与其等值的八进制数
SqStack S;InitStack(S);int N;printf("Please input the N:");scanf_s("%d",&N);while(N){Push(S, N %8);
N = N /8;}print_SqStack(S);while(!StackEmpty(S)){int e;Pop(S, e);printf("%d", e);}}