1.定义
所谓共享栈就是利用一个数组实现两个栈. 先来看一下共享栈的数据结构
typedef struct SharedStack
{int top1;int top2;SeqStackType* data;
}SharedStack;
2. 初始化
void SharedStackInit(SharedStack* stack)
{if(stack == NULL){return;//非法输入}stack -> top1 = 0;stack -> top2 = MAXSIZE;stack -> data = (SeqStackType*)malloc(sizeof(MAXSIZE));if(stack -> data == NULL){return;//内存申请失败}
}
3. 第一个栈入栈
void SharedStackPush1(SharedStack* stack, SeqStackType value)
{if(stack == NULL){return;//非法输入}if(stack -> top1 == stack -> top2){return;//共享栈已满}stack -> data[stack -> top1++] = value;
}
4. 第二个栈入栈
void SharedStackPush2(SharedStack* stack, SeqStackType value)
{if(stack == NULL){return;//非法输入}if(stack -> top1 == stack -> top2){return;//共享栈已满}stack -> data[--stack -> top2] = value;
}
5. 第一个栈出栈
void SharedStackPop1(SharedStack* stack)
{if(stack == NULL){return;//非法输入}if(stack -> top1 == 0){return;//栈空}stack -> top1--;
}
6. 第二个栈出栈
void SharedStackPop2(SharedStack* stack)
{if(stack == NULL){return;//非法输入}if(stack -> top2 == MAXSIZE){return;//栈空}stack -> top2++;
}
7. 取第一个栈的栈顶元素
int SharedStackTop1(SharedStack* stack, SeqStackType* value)
{if(stack == NULL || value == NULL){return 0;//非法输入}*value = stack -> data[stack -> top1 -1];return 1;
}
8. 取第二个栈的栈顶元素
int SharedStackTop2(SharedStack* stack, SeqStackType* value)
{if(stack == NULL || value == NULL){return 0;}*value = stack -> data[stack -> top2];return 1;
}