C++实现共享栈

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/SoftpaseFar/article/details/102415366
#include <iostream>

using namespace std;

#define MaxSize 15
typedef int ElemType;


//实现共享栈
struct SqStack {//栈定义
    ElemType elem[MaxSize];
    int top[2];//top[0]代表s0的栈顶,top[1]代表s1的栈顶
};
SqStack S;

//初始化
void InitStack(SqStack &S) {
    S.top[0] = -1;
    S.top[1] = MaxSize;
}

//入栈
int Push(SqStack &S, int num, int x) {//指定元素进入第num个栈
    if (S.top[0] + 1 < S.top[1]) {//判断是否满了
        if (num == 0) {
            ++S.top[0];
            S.elem[S.top[0]] = x;
            return 1;
        } else if (num == 1) {
            --S.top[1];
            S.elem[S.top[1]] = x;
            return 1;
        } else {
            return -1;
        }
    } else {
        return 1;
    }
}

//出栈
int Pop(SqStack &S, int num, int &x) {
    if (num == 0) {
        if (S.top[1] != -1) {
            x = S.elem[S.top[0]];
            --S.top[0];
            return 1;
        } else {
            return 0;
        }
    } else if (num == 1) {
        if (S.top[1] != MaxSize) {
            x = S.elem[S.top[1]];
            ++S.top[1];
            return 1;
        } else {
            return 0;
        }
    } else {
        return -1;
    }
}

//获取栈顶元素元素
int GetElem(SqStack S, int num, int &x) {
    if (num == 0) {
        if (S.top[0] != -1) {
            x = S.elem[S.top[0]];
        } else {
            return -1;
        }
    } else if (num == 1) {
        if (S.top[1] != MaxSize) {
            x = S.elem[S.top[1]];
        } else {
            return -1;
        }
    } else {
        return -1;
    }
}

int main() {
    //测试数据略
    return 0;
}

猜你喜欢

转载自blog.csdn.net/SoftpaseFar/article/details/102415366
今日推荐