共享栈为空的状态,左右两栈的栈顶指针都在两端,也就是各自栈的栈底
代码当中测试栈满的时候的状态图
共享栈的数据结构
typedef struct{
int elem[maxSize];
int top[2];
}SqStack;
入共享栈的操作,因为共享栈是由两个栈组成的,因此我们在入栈的时候需要选择入栈的编号,也就是stNo,同时要注意栈满的特殊情况
int push(SqStack &st, int stNo, int x){
if (st.top[0]+1<st.top[1]){ //先判断栈是否是满的
if (stNo==0){
++(st.top[0]);
st.elem[st.top[0]]=x;
return 1; //入栈成功
}else if (stNo==1){
--(st.top[1]);
st.elem[st.top[1]]=x;
return 1;
}else
return -1;
}else
return 0; //入栈失败
}
出栈操作,同样需要指定出栈的编号,同时还需要处理指定的栈栈中元素是否为空的特殊情况
int pop(SqStack &st, int stNo, int &x){
if (stNo==0){
if (st.top[0]!=-1){ //验证栈是否为空
x=st.elem[st.top[0]];
--(st.top[0]);
return 1; //出栈成功
}else
return 0; //出栈失败
}else if (stNo==1){
if (st.top[1]!=maxSize){
x=st.elem[st.top[1]];
++(st.top[1]);
return 1;
}else
return 0; //出栈失败
}else
return -1; //栈编号输入错误
}
判断共享栈是否是满的
int isEmpty(SqStack st){
if (st.top[0]+1==st.top[1])
return 1;
else
return 0;
}
我只写了这三种基本操作,此外还可以自行添加返回栈顶元素的操作
下为完整的代码,可直接运行
#include <stdio.h>
#define maxSize 5
typedef struct{
int elem[maxSize];
int top[2];
}SqStack;
//初始化
void init(SqStack &st){
st.top[0]=-1;
st.top[1]=maxSize;
}
//入栈操作
//stNo是栈的编号,x是入栈元素
int push(SqStack &st, int stNo, int x){
if (st.top[0]+1<st.top[1]){ //先判断栈是否是满的
if (stNo==0){
++(st.top[0]);
st.elem[st.top[0]]=x;
return 1; //入栈成功
}else if (stNo==1){
--(st.top[1]);
st.elem[st.top[1]]=x;
return 1;
}else
return -1;
}else
return 0; //入栈失败
}
//出栈
int pop(SqStack &st, int stNo, int &x){
if (stNo==0){
if (st.top[0]!=-1){ //验证栈是否为空
x=st.elem[st.top[0]];
--(st.top[0]);
return 1; //出栈成功
}else
return 0; //出栈失败
}else if (stNo==1){
if (st.top[1]!=maxSize){
x=st.elem[st.top[1]];
++(st.top[1]);
return 1;
}else
return 0; //出栈失败
}else
return -1; //栈编号输入错误
}
//判断是否栈满,1为满,0为不满
int isEmpty(SqStack st){
if (st.top[0]+1==st.top[1])
return 1;
else
return 0;
}
//打印栈
void printStack(SqStack st){
printf ("当前栈中元素是:");
for (int i=0; i<=st.top[0]; i++){
printf ("%d ", st.elem[i]);
}
for (int i=st.top[1]; i<maxSize; i++){
printf ("%d ", st.elem[i]);
}
printf ("\n");
}
int main(){
SqStack st;
init(st);
push(st, 0, 5);
push(st, 0, 2);
push(st, 0, 3);
push(st, 1, 6);
push(st, 1, 9);
push(st, 1, 8);
if (isEmpty(st)){
printf ("栈满!\n");
}
int x;
pop(st, 1, x);
printf ("出栈元素是:%d\n", x);
printStack(st);
return 0;
}