zoukankan      html  css  js  c++  java
  • 共享栈的实现

    //共享栈的实现 -- 是一个顺序栈
    /*
     * c++实现,面向过程
     * date:2021-03-08
     * auther:nanfengnan
     * 共享栈的定义:栈底定义在顺序栈的两端,两个栈顶向两方延伸
     * 方法:
     *  初始化一个空栈
     *  入栈
     *  出栈
     *  判断栈空
     *  得到栈顶元素
     *  销毁栈
     */
    #include<iostream>
    #define MaxSize 50
    using namespace std;
    typedef int ElemType;
    //数据结构定义
    typedef struct node{
        ElemType data[MaxSize];
        int top1;  //定义的指针一
        int top2;  //定义的指针二
    }Share_stack;
    
    void InitStack(Share_stack &S)
    {
        //初始化一个空栈
        S.top1=-1;  //1号栈空
        S.top2=MaxSize; //2号栈空
    }
    
    //1号进站
    int Push_1(Share_stack &S,ElemType x)
    {
        //入栈,判断栈是否满了
        if(S.top2-S.top1==1){
            return -1; //栈满了
        }
        else{
            S.data[++S.top1]=x;
            return 0;
        }
    }
    //2号进站
    int Push_2(Share_stack &S,ElemType x)
    {
        //入栈,判断栈是否满了
        if(S.top2-S.top1==1){
            return -1; //栈满了
        }
        else{
            S.data[--S.top2]=x;
            return 0;
        }
    }
    //1号出栈
    int Pop_1(Share_stack &S,ElemType &x)
    {
        //出栈,判断是否栈空
        if(S.top1==-1){
            return -1;  //1号栈空
        }
        else{
            x=S.data[S.top1--];
            return 0;
        }
    }
    //2号出栈
    int Pop_2(Share_stack &S,ElemType &x)
    {
        //出栈,判断是否栈空
        if(S.top2==MaxSize){
            return -1;  //1号栈空
        }
        else{
            x=S.data[S.top1++];
            return 0;
        }
    }
    //得到1号栈顶元素
    int GetTop_1(Share_stack &S,ElemType &x)
    {
        //判断栈空
        if (S.top1==-1){
            return -1;
        }
        else{
            x=S.data[S.top1];
            return 0;
        }
    }
    //得到12号栈顶元素
    int GetTop_2(Share_stack &S,ElemType &x)
    {
        //判断栈空
        if (S.top1==MaxSize){
            return -1;
        }
        else{
            x=S.data[S.top2];
            return 0;
        }
    }
    int main()
    {
        Share_stack S;
        InitStack(S);
        Push_1(S,12);
        Push_2(S,13);
        ElemType x;
        GetTop_1(S,x);
        cout<<x<<endl;
        GetTop_2(S,x);
        cout<<x<<endl;
        return 0;
    }
  • 相关阅读:
    基础【五】字典的操作方法
    基础【四】列表的操作方法
    基础【三】字符串的操作方法
    基础【二】while循环及基本运算符
    基础【一】基础数据类型
    C++ string 深拷贝 与 浅拷贝
    多进程引用的动态链接库中的全局变量问题
    C++ 在类里面使用多线程技术
    openwrt 解决包依赖关系
    lua 的元表与元方法
  • 原文地址:https://www.cnblogs.com/nanfengnan/p/14500540.html
Copyright © 2011-2022 走看看