#include <stdlib.h>
#include <stdio.h>
#define MAXSIZE 100
typedef int ElemType;
typedef struct S_Stack{
ElemType *top;
ElemType *base;
int InitSize;
}Stack;
//1.栈的初始化
int InitStack(Stack &s){ //&????
s.base=new ElemType[MAXSIZE];
s.top=s.base;
s.InitSize=MAXSIZE;
}
//2.判断栈是否为空
int StackEmpty(Stack s){
if(s.top==s.base)
return 1;
else
return 0;
}
//3.栈的长度
int StackLength(Stack s){
return s.top-s.base;
}
//4.进栈
int Push(Stack* S, ElemType e){
//首先 判断栈满没有 如果满了就增量分配
if (S->top - S->base == S->InitSize){
return 0;
}
*S->top++ = e;
return 1; //入栈成功则返回1
}
//5.出栈
int Pop(Stack* S, ElemType* e){
//首先,判断栈是不是空的,如果是空的则返回0
if (S->top == S->base) return 0;
*e = *(--S->top); //将栈顶元素赋给e,栈顶指针下移
return 1; //出栈成功则返回1
}
//6.销毁栈
int DestroyStack(Stack &s){
if(s.base){
delete s.base;
s.InitSize=0;
s.base=s.top=NULL;
}
}
//7.清空栈
int ClearStack(Stack &s){
if(s.base)
s.top=s.base;
return 1;
}
// 8.取栈顶元素
int GetTopStack(Stack s){
if(s.base!=s.top){
return *(s.top-1);
}
}
//9.遍历栈元素
void PrintStack(Stack S){
while (S.top > S.base)
printf("%d ", *(--S.top));
printf("\n");
}
int main(){
Stack S;
ElemType e;
int i = 0;
InitStack(S); //初始化
printf("初始化成功!\n执行10次入栈操作:\n");
for (i = 0; i < 10; i++){
e = rand() % 90 + 10;
printf("第%-2d次:元素%d入栈\n", i + 1, e);
Push(&S, e); //入栈
}
printf("\n打印当前栈:");
PrintStack(S); //遍历并打印
printf("\n执行5次出栈操作:\n");
for (i = 0; i < 5; i++){
if (Pop(&S, &e) == 1){ //出栈
printf("第%d次:出栈元素是%d\t打印当前栈:", i + 1, e);
PrintStack(S); //遍历并打印
}
}
printf("栈顶元素为:%d\n",GetTopStack(S));
//DestroyStack(S);
printf("当前栈长度为%d\n", StackLength(S));
PrintStack(S); //遍历并打印
ClearStack(S);
PrintStack(S); //遍历并打印
printf("清空后当前栈长度为%d\n", StackLength(S));
return 0;
}