#include<bits/stdc++.h>
#define ElemType int
#define MaxSize 50
using namespace std;
typedef struct SeqStack{
ElemType data[MaxSize];
int top0,top1;
}SharedSeqStack;
//初始化
void InitStack(SharedSeqStack &s){
s.top0 = -1;
s.top1 = MaxSize;
}
//0号栈入栈
bool Push0(SharedSeqStack &s,ElemType e0){
if(s.top1-s.top0 == 1) return false;
s.data[++s.top0] = e0;//栈顶先++再入栈
return true;
}
//1号栈入栈
bool Push1(SharedSeqStack &s,ElemType e1){
if(s.top1-s.top0 == 1) return false;
s.data[--s.top1] = e1;//栈顶先--再入栈
return true;
}
//0号栈出栈
bool Pop0(SharedSeqStack &s,ElemType &x){
if(s.top0==-1) return false;
x = s.data[s.top0--];//先把元素给x传回去再--
return true;
}
//1号栈出栈
bool Pop1(SharedSeqStack &s,ElemType &x){
if(s.top1==MaxSize) return false;
x = s.data[s.top1++];//先把元素给x传回去再++
return true;
}
//取栈顶
bool GetTop(SharedSeqStack s,ElemType &x1,ElemType &x2){
if(s.top0==-1||s.top1==MaxSize) return false;
x1 = s.data[s.top0];
x2 = s.data[s.top1];
return true;
}
int main(){
//声明共享栈
SharedSeqStack s;
//初始化
InitStack(s);
//入栈
int i = 1,x = 0,y = 0;
while(i<=20){
Push0(s,i);//1到20
i++;
}
while(i<=50){
Push1(s,i);//21到50
i++;
}
//取栈顶
if(GetTop(s,x,y)){
cout<<"stack0:"<<x<<"\n"<<"stack1:"<<y<<endl;
}
//出栈
i=1;
while (i<=30){
Pop1(s,y);
printf("stack1:%d\n",y);
i++;
}
return 0;
}
共享栈的实现(c/c++)
最新推荐文章于 2024-07-20 19:39:28 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)