代码
#define ElemType int
#define Status int
#define OK 0
#define OVERFLOW -1
#define ERROR -1
#define MAXSIZE 100
using namespace std;
#include<bits/stdc++.h>
//结构定义
typedef struct {
ElemType *base; //栈底指针
ElemType *top; //栈顶指针
int stacksize; //最大容量
}SqStack;
//初始化栈
Status InitStack(SqStack &S) {
S.base = new ElemType[MAXSIZE];
if(!S.base) return ERROR;
S.top = S.base;
S.stacksize = MAXSIZE;
return OK;
}
//入栈
Status Push(SqStack &S,ElemType e){
//判断栈满了没有
if(S.top - S.base == S.stacksize ) return ERROR;
*S.top = e; //赋值
S.top++; //指针后移
return OK;
}
//出栈 通过e返回栈顶元素
Status Pop(SqStack &S,ElemType &e){
//判断到栈底没有
if(S.top==S.base) return ERROR;
S.top--;
e = *S.top;
// e =*(--S.top);
return OK;
}
//取栈顶元素
ElemType GetTop(SqStack S) {
//空栈 没东西
if(S.top==S.base) return ERROR;
return *(--S.top);
}
int main() {
SqStack S;
InitStack(S);
cout << "入栈0 1 2 3 4" << endl;
for(int i =0;i<5;i++) {
//入栈
Push(S,i);
}
//获取栈顶元素
ElemType e= GetTop(S);
cout << "栈顶元素是:" <<e << endl;
cout << "出栈" << endl;
for(int i =0;i<5;i++) {
//入栈
Pop(S,e);
cout << e << endl;
}
return 0;
}
运行截图
版权属于:本文为原创文章,版权归 猫先生 所有
本文链接:https://loli.rip/index.php/archives/216/
转载时须注明出处及本声明