/*
共享栈
*/
#define MaxSize 10 // 栈中元素的最大个数
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
typedef int ElemType;
struct ShStack {
ElemType data[MaxSize]; // 静态数组
int top1; // 栈顶指针
int top2;
};
// 初始化栈
void InitStack(ShStack &S) {
S.top1 = -1;
S.top2 = MaxSize; // 初始化指针,指向栈顶
}
// 判断栈空
bool StackEmpty(ShStack S) {
if (S.top1 == -1 && S.top2 == MaxSize) {
return true;
} else {
return false;
}
}
// 判断栈满
bool StackFull(ShStack S) {
if (S.top1 + 1 == S.top2) {
return true;
} else {
return false;
}
}
// 栈1入栈
bool Push1(ShStack &S, ElemType x) {
if (StackFull(S)) {
return false;
} else {
S.top1++;
S.data[S.top1] = x; // S.top0指向栈顶
return true;
}
}
// 栈2入栈
bool Push2(ShStack &S, ElemType x) {
if (StackFull(S)) {
return false;
} else {
S.top2--;
S.data[S.top2] = x; // S.top1指向栈顶
return true;
}
}
// 栈1出栈
bool Pop1(ShStack &S, ElemType &x) {
if (S.top1 == -1) { // 栈空
return false;
} else {
x = S.data[S.top1--]; // 先赋值再--
return true;
}
}
// 栈2出栈
bool Pop2(ShStack &S, ElemType &x) {
if (S.top2 == MaxSize) { // 栈空
return false;
} else {
x = S.data[S.top2++]; // 先赋值再++
return true;
}
}
// 读取栈1栈顶元素
bool GetTop1(ShStack S, ElemType &x) {
if (S.top1 == -1) {
return false;
} else {
x = S.data[S.top1];
return true;
}
}
// 读取栈2栈顶元素
bool GetTop2(ShStack S, ElemType &x) {
if (S.top2 == MaxSize) {
return false;
} else {
x = S.data[S.top2];
return true;
}
}
// 栈的置空
void DestroyStack(ShStack &S) {
S.top1 = -1;
S.top2 = MaxSize;
}
int main() {
// ShStack *S = (ShStack*)malloc(sizeof(ShStack)); // malloc方法申请空间,此方法需要将后面的结构体S改写为指针*S
ShStack S;
ElemType top1, top2, pop1, pop2;
InitStack(S);
cout << "栈是否为空:" << StackEmpty(S) << endl;
for (int i = 0; i < 5; i++) { // 栈1入栈
Push1(S, i);
}
GetTop1(S, top1);
cout << "栈1栈顶元素:" << top1 << endl;
for (int j = 10; j < 20; j++) { // 栈2入栈
Push2(S, j);
}
GetTop2(S, top2);
cout << "栈2栈顶元素:" << top2 << endl;
cout << "栈是否存满:" << StackFull(S) << endl;
Pop1(S, pop1);
cout << "栈1出栈元素:" << pop1 << endl;
Pop2(S, pop2);
cout << "栈2出栈元素:" << pop2 << endl;
GetTop1(S, top1);
cout << "栈1栈顶元素:" << top1 << endl;
cout << "栈是否存满:" << StackFull(S) << endl;
DestroyStack(S);
}