总结归纳
- 共享栈的实现,就是申请一块内存,两个栈共同使用同一块内存空间,一个从左往右存,一个从右往左存。
- 共享栈存满的判断条件是:S.top1 + 1 == S.top2(指针指向栈顶的情况下)。
代码实现
#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;
}
}
bool Push1(ShStack &S, ElemType x) {
if (StackFull(S)) {
return false;
} else {
S.top1++;
S.data[S.top1] = x;
return true;
}
}
bool Push2(ShStack &S, ElemType x) {
if (StackFull(S)) {
return false;
} else {
S.top2--;
S.data[S.top2] = x;
return true;
}
}
bool Pop1(ShStack &S, ElemType &x) {
if (S.top1 == -1) {
return false;
} else {
x = S.data[S.top1--];
return true;
}
}
bool Pop2(ShStack &S, ElemType &x) {
if (S.top2 == MaxSize) {
return false;
} else {
x = S.data[S.top2++];
return true;
}
}
bool GetTop1(ShStack S, ElemType &x) {
if (S.top1 == -1) {
return false;
} else {
x = S.data[S.top1];
return true;
}
}
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;
ElemType top1, top2, pop1, pop2;
InitStack(S);
cout << "栈是否为空:" << StackEmpty(S) << endl;
for (int i = 0; i < 5; i++) {
Push1(S, i);
}
GetTop1(S, top1);
cout << "栈1栈顶元素:" << top1 << endl;
for (int j = 10; j < 20; j++) {
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);
}