#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef int SElemType;
typedef struct {
SElemType *base;
SElemType *top;
int stackSize;
}SqStack;
SqStack *InitStack(SqStack *S);//初始化
SqStack *DestroyStack(SqStack*S);//销毁
void ClearStack(SqStack*S);//清空
int StackEmpty(SqStack*S);//判空
int StackLength(SqStack*S);//栈长度
SElemType GetTop(SqStack*S);//获取栈顶元素,不修改指针位置
int Push(SqStack*S, SElemType e);//插入栈顶
int Pop(SqStack *S, SElemType *e);//删除栈顶
void StackTraverse(SqStack *S);//从栈顶依次遍历
//初始化,返回指向栈的指针
SqStack * InitStack(SqStack *S){
S = (SqStack *)malloc(sizeof(SqStack));
S->base = (SElemType *)malloc(sizeof(SElemType)*MAXSIZE);
if(!S->base){
printf("空间不足初始化失败\n");
return NULL;
}
S->top = S->base;
S->stackSize = MAXSIZE;
printf("初始化成功\n");
return S;
}
//销毁
SqStack *DestroyStack(SqStack*S){
free(S->base);
free(S);
printf("已销毁\n");
return NULL;
}
//清空
void ClearStack(SqStack*S){
printf("清空\n");
SElemType *p = S->top;
while(p >= S->base){
*p--=0;
}
printf("清空成功\n");
}
//判空
int StackEmpty(SqStack*S){
return (S->base == S->top);
}
//返回栈长度
int StackLength(SqStack*S){
return S->top-S->base;
}
//获取栈顶元素,不修改指针位置
SElemType GetTop(SqStack*S){
if(S->top != S->base)
return *(S->top - 1);
}
//插入栈顶,返回是否插入成功的状态
int Push(SqStack*S, SElemType e){
if(S->top - S->base == S->stackSize){
printf("栈已满,插入失败\n");
return 0;
}
//先赋值后动指针
*S->top++=e;
printf("%d元素入栈成功\n", e);
return 1;
}
//删除栈顶,返回是否删除成功的状态
int Pop(SqStack *S, SElemType *e){
//栈空
if(S->top == S->base){
printf("空栈,删除失败\n");
return 0;
}
//先动指针后赋值
*e = *--S->top;
printf("%d出栈成功\n", *e);
return 1;
}
//从栈顶依次遍历
void StackTraverse(SqStack *S){
SElemType *p = S->top;
while(p > S->base){
p--;
printf("%d ", *p);
}
printf("\n");
}
int main()
{
SqStack *S = NULL;
SElemType e;
//初始化测试
S = InitStack(S);
// //判空测试
// if(StackEmpty(S)) printf("空栈\n");
//
//插入测试
Push(S, 1);
Push(S, 3);
Push(S, 2);
Push(S, 4);
Push(S, 7);
// //遍历测试
// StackTraverse(S);
//
// //出栈测试
// Pop(S, &e);
//// printf("测试e是否改变:%d\n",e);
// StackTraverse(S);
//
// //栈长测试
// printf("栈长%d\n",StackLength(S));
//
// //获取栈顶元素测试
// e = GetTop(S);
// printf("栈顶元素是%d\n", e);
// StackTraverse(S);
//
// //清空测试
// ClearStack(S);
// if(StackEmpty(S)) printf("空栈\n");
// StackTraverse(S);
//销毁测试
S = DestroyStack(S);
StackTraverse(S);
return 0;
}