#include <iostream>
#include <cstdlib>
#define MAXSIZE 20
#define N 10
using namespace std;
//方法1
//静态栈的创建及其出栈入栈
//注意点:栈的0位置默认不存放数据,从下标1开始操作
typedef struct sqstack
{
int *elem;
int top;
}SqStack;
/*****************初始化静态栈******************/
void InitStack(SqStack & s)
{
s.elem =new int[MAXSIZE];
if(s.elem == NULL)
{
cout<<"内存分配失败!!!退出程序"<<endl;
exit(0); //需引入头文件<cstdlib>
}
s.top=0;
}
/******************压栈*************************/
//进栈是从下标1开始存放,0位置不存放数据
void Push(SqStack &s , int e)
{
if(s.top >= MAXSIZE-1)
{
cout<<"栈已满!!!"<<endl;
}else
{
s.top++;
s.elem[s.top]=e;
}
}
/******************出栈*************************/
void Pop(SqStack &s , int &e)
{
if(s.top <1)
cout<<"栈已空!!!"<<endl;
else
{
e=s.elem[s.top];
s.top--;
}
}
/******************显示栈*************************/
void ShowStack(SqStack &s)
{
if(s.top <1)
cout<<"栈是空的!!!"<<endl;
else
{
for(int i = s.top; i >= 1; i--)
cout<<i<<" ";
}
}
int main()
{
SqStack s;
InitStack(s);
for(int i=1;i<N;i++)
Push(s,i);
ShowStack(s);
return 0;
}
C++数据结构-栈的初始化及其压栈和出栈-方法1

最新推荐文章于 2024-05-06 22:16:21 发布
