初始化一个数据元素为整形的链栈,并实现进栈、出栈、获得栈顶元素等操作。
通过控制台将1,2,3,4,5进栈,出栈两次,获得栈顶元素并输出,6进栈,打印栈内的所有内容。
#include<iostream>
#include<cstdio>
#define MAXSIZE 100
#define OK 1
#define ERROR 0
using namespace std;
typedef struct //定义顺序栈
{
int *base; //栈底指针
int *top; //栈顶指针
int Stacksize; //栈的可用最大容量
}SqStack;
int InitStack(SqStack &S) //初始化栈
{
S.base=new int[MAXSIZE];
if(!S.base) return 0;
S.top=S.base; //初始为空栈
S.Stacksize=MAXSIZE;
return OK;
}
int Push(SqStack &S,int e) //入栈,e不为引用传递
{
if(S.top-S.base==S.Stacksize) return ERROR;
*S.top++=e; //先将e的值赋给栈顶,然后栈顶指针加1
return OK;
}
int Pop(SqStack &S,int &e) //出栈,引用传递
{
if(S.top==S.base) return ERROR;
e=*--S.top; //先将栈顶指针减1,之后将值赋给e
return OK;
}
int GetTop(SqStack &S) //取栈顶元素
{
if(S.top!=S.base)
return *(S.top-1);
}
int main()
{
SqStack S;
InitStack(S);
int a,i,b;
cout<<"入栈"<<endl;
for(i=0;i<5;i++)
{
scanf("%d",&a);
Push(S,a);
}
cout<<"出栈1位"<<endl;
Pop(S,b);
cout<<b<<endl;
cout<<"再出栈1位"<<endl;
Pop(S,b);
cout<<b<<endl;
cout<<"取当前栈顶元素"<<endl;
cout<<GetTop(S)<<endl;
Push(S,6);
cout<<"剩余元素全部出栈"<<endl;
while(Pop(S,b))
cout<<b<<' ';
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/2132699700da50bb2b20745005c132ee.png)