共享栈
有问题可以在评论区一起探讨
#include<stdio.h>
#define MaxSize 10
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];
int top0; //0号栈栈顶指针
int top1; //1号栈栈顶指针
}ShStack;
//初始化栈
void InitStack(ShStack&);
//判断栈空
bool StackEmpty(ShStack);
//判断栈空(0号栈)
bool StackEmpty_0(ShStack);
//判断栈空(1号栈)
bool StackEmpty_1(ShStack);
//判断栈满
bool StackFull(ShStack);
//压栈(0号栈)
bool Push_0(ShStack&, ElemType);
//压栈(1号栈)
bool Push_1(ShStack&, ElemType);
//出栈(0号栈)
bool Pop_0(ShStack&, ElemType&);
//出栈(1号栈)
bool Pop_1(ShStack&, ElemType&);
//栈顶元素(0号栈)
bool GetTop_0(ShStack, ElemType&);
//遍历栈(0号栈)
void Traverse_0(ShStack);
//遍历栈(1号栈)
void Traverse_1(ShStack);
int main(void) {
ShStack S;
InitStack(S);
//判断共享栈是否为空
if (StackEmpty(S)) {
printf("共享栈空!\n");
}
//0号栈压栈
for (int i = 1; i <= 5; i++) {
Push_0(S, i);
}
//1号栈压栈
for (int i = 6; i <= 10; i++) {
Push_1(S, i);
}
if (Push_0(S, 999)) {
printf("栈满!\n");
}
if (Push_1(S, 999)) {
printf("栈满!\n");
}
//遍历0号栈
printf("0号栈:\n");
Traverse_0(S);
//遍历1号栈
printf("1号栈:\n");
Traverse_1(S);
ElemType x;
//0号栈出栈
for (int i = 1; i <= 3; i++) {
if (!Pop_0(S, x)) {
printf("0号栈空!\n");
}
if (!Pop_1(S, x)) {
printf("1号栈空!\n");
}
}
//遍历0号栈
printf("0号栈:\n");
Traverse_0(S);
//遍历1号栈
printf("1号栈:\n");
Traverse_1(S);
return 0;
}
void InitStack(ShStack& S) {
S.top0 = -1;
S.top1 = MaxSize;
}
bool StackEmpty(ShStack S) {
return StackEmpty_0(S) && StackEmpty_1(S);
}
bool StackEmpty_0(ShStack S) {
return S.top0 == -1;
}
bool StackEmpty_1(ShStack S) {
return S.top1 == MaxSize;
}
bool StackFull(ShStack S) {
return S.top0 + 1 == S.top1;
}
bool Push_0(ShStack& S, ElemType x) {
if (StackFull(S)) {
return false;
}
S.data[++S.top0] = x;
return true;
}
bool Push_1(ShStack& S, ElemType x) {
if (StackFull(S)) {
return false;
}
S.data[--S.top1] = x;
return true;
}
bool Pop_0(ShStack& S, ElemType& x) {
if (StackEmpty_0(S)) {
return false;
}
x = S.data[S.top0--];
return true;
}
bool Pop_1(ShStack& S, ElemType& x) {
if (StackEmpty_1(S)) {
return false;
}
x = S.data[S.top1++];
return true;
}
bool GetTop_0(ShStack S, ElemType& x) {
if (StackEmpty_0(S)) {
return false;
}
x = S.data[S.top0];
return true;
}
bool GetTop_1(ShStack S, ElemType& x) {
if (StackEmpty_1(S)) {
return false;
}
x = S.data[S.top1];
return true;
}
void Traverse_0(ShStack S) {
if (StackEmpty_0(S)) {
printf("0号栈空!\n");
return;
}
int top0 = S.top0;
while (top0 >= 0) {
printf("%d\t", S.data[top0--]);
}
printf("\n");
}
void Traverse_1(ShStack S) {
if (StackEmpty_1(S)) {
printf("1号栈空!\n");
return;
}
int top1 = S.top1;
while (top1 < MaxSize) {
printf("%d\t", S.data[top1++]);
}
printf("\n");
}