数据结构-栈的静态顺序存储表示-初始化压栈弹栈

时间:2021-05-16 10:26:48

和上一个博客,动态方式一样

#include<iostream>
#include<stdlib.h>
#define MAX_STACKSIZE 100
#define OK 1
#define ERROR 0
using namespace std;

typedef struct sqstack
{
int stack_array[MAX_STACKSIZE];
int top;
int bottom;
}SqStack;

SqStack s;

void init_stack()
{
s.top=s.bottom=0;
}

int insert_stack(int num)
{
if(s.top>=MAX_STACKSIZE-1) return ERROR;
s.stack_array[++s.top]=num;
return OK;
}

int pop_stack(int *e)
{
if(s.top==0) return ERROR;
*e=s.stack_array[s.top--];
return OK;
}

int show_stack()
{
if(s.top==s.bottom) return ERROR;
for(int i=1;i<=s.top;i++)
{
cout<<s.stack_array[i]<<" ";
}
cout<<endl;
return OK;
}

int main()
{
init_stack();
while(1)
{
int temp;
cout<<"压栈1弹栈2显示3"<<endl;
cin>>temp;
if(temp==1)
{
int num;
cin>>num;
if(!insert_stack(num))
{
cout<<"插入失败"<<endl;
}
}
else if(temp==2)
{
int num;
if(pop_stack(&num))
{
cout<<"弹出元素:"<<num<<endl;
}
else cout<<"弹栈失败"<<endl;
}
else
{
if(!show_stack()) cout<<"空栈"<<endl;
}
}
return 0;
}
/*
1
12
1
34
1
2
1
34
1
67
1
567
3
1
234
1
3
2
2
2
2
2
2


*/