共享栈的实现

//共享栈的实现 -- 是一个顺序栈
/*
 * 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;
}

 

posted @ 2021-03-08 16:44  nanfengnan  阅读(274)  评论(0编辑  收藏  举报