MaxSize-1 向左增长;栈满:top1 + 1 == top2(两栈顶指针相邻)。共享栈(Shared Stack)是指两个栈共享同一片连续存储空间的数据结构。
#define MaxSize 100
typedef struct {
ElemType data[MaxSize];
int top1; // 栈1的栈顶指针,初始值为 -1
int top2; // 栈2的栈顶指针,初始值为 MaxSize
} SharedStack;
void InitStack(SharedStack *S) {
S->top1 = -1; // 栈1为空
S->top2 = MaxSize; // 栈2为空
}
bool Push(SharedStack *S, ElemType x, int stackNum) {
if (S->top1 + 1 == S->top2) // 栈满
return false;
if (stackNum == 1)
S->data[++S->top1] = x; // 栈1入栈
else
S->data[--S->top2] = x; // 栈2入栈
return true;
}
bool Pop(SharedStack *S, ElemType *x, int stackNum) {
if (stackNum == 1) {
if (S->top1 == -1) return false; // 栈1空
*x = S->data[S->top1--];
} else {
if (S->top2 == MaxSize) return false; // 栈2空
*x = S->data[S->top2++];
}
return true;
}
题目:$MaxSize=8$ 的共享栈,执行:①栈 1 压入 A,B,C;②栈 2 压入 X,Y;③栈 1 弹出;④栈 2 压入 Z。
步骤 4 结束后:$top1=1,\; top2=5$。判满:$top1+1=2 \neq top2=5$,未满;还可容纳 $top2-top1-1 = 5-1-1 = 3$ 个元素(下标 2、3、4 三个空位)。
--top2。--top2,从数组末尾向左增长。(暂无关联知识点)