共享栈的实现(c/c++)

本文详细介绍了C++中使用结构体定义的共享栈(SharedSeqStack),包括初始化、0号栈和1号栈的入栈、出栈以及取栈顶操作。代码示例展示了栈的操作过程。
摘要由CSDN通过智能技术生成
#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;
}


  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值