#include<iostream>
using namespace std;
#define Maxsize 100 //预分配空间
typedef struct SqStack{
int *base;
int *top;
}SqStack;
bool InitStack(SqStack &S) //初始化空栈
{
S.base = new int[Maxsize];
if(!S.base)
return 0;
S.top = S.base;
return 1;
}
bool Push(SqStack &S, int e) //入栈
{
if(S.top-S.base==Maxsize)
return 0;
*(S.top++)=e;
return 1;
}
bool Pop(SqStack &S, int &e) //出栈
{
if(S.base==S.top)
return 0;
e=*(--S.top); //s.top=s.top-1 -> e=*(s.top)
return 1;
}
int GetTop(SqStack S) //返回栈顶元素
{
if(S.top != S.base)
return *(S.top-1);
else
return -1;
}
int main()
{
int n, x;
SqStack S;
InitStack(S); //初始化
cout <<"请输入元素个数n:" <<endl;
cin>>n;
/*int &m=n;
cout <<m<< endl;*/ //引用&在左侧,地址&在右侧。同样的道理,3=a是不被允许的,变量一般为左值,常量一定为右值。
/*int &m=n;
cout <<&n<< endl;*/
cout <<"请依次输入n个元素,依次入栈:" <<endl;
while(n--)
{
cin>>x;
Push(S,x);
}
cout <<"元素依次出栈:" <<endl;
while(S.top!=S.base)
{
cout<<GetTop(S)<<"\t"; //输出栈顶元素
Pop(S, x); //栈顶元素出栈
}
return 0;
}
数据结构与算法365天训练营—顺序栈的基本操作
于 2023-08-07 10:34:40 首次发布