1.两栈共享数据结构定义
#define MAXNUM
typedef struct{
Elemtype stack[MAXNUM];
int lefttop;//左栈栈顶位置指示器
int righttop;//右栈栈顶位置指示器
}dupsqstack;
左栈入栈时,栈顶指针+1,右栈入栈时,栈顶指针-1;Elemtype是element type("元素的类型")的简化体,一种结构中,元素的类型不一定为整型,字符型或浮点型,“Elemtype”代表了所有可能的数据类型
判断栈满的条件:s->lefttop + 1 == s->righttop;
2.共享栈操作
//初始化
dupsqstack* initDupStack() {
//创建两个共享临界空间的空栈 由指针s指出
/*if ((s = (dupsqstack*)malloc(sizeof(dupsqstack))) == NULL) {
return NULL;
}*/
dupsqstack *s;
s = (dupsqstack*)malloc(sizeof(dupsqstack));
s->lefttop = -1;
s->righttop = MAXNUM;
return s;
}
//入栈操作
int pushDupStack(dupsqstack *s, char status, Elemtype x) {
//将数据元素压入左栈或者右栈
if (s->lefttop + 1 == s->righttop) {//栈满
return NULL;
}
else if(status=='L'){//左栈进栈
s->stack[++s->lefttop] = x;
}
else if (status == 'R') {//右栈进栈
s->stack[--s->righttop] = x;
}
else {
return NULL;
}
return 1;
}
//出栈操作
Elemtype popDupStack(dupsqstack *s, char status) {
//从左栈或者右栈退出栈顶元素
if (status == 'L') {
if (s->lefttop < 0) {//左栈为空
return NULL;
}
else {//左栈出栈
return (s->stack[s->lefttop--]);
}
}
else if (status == 'R') {
if (s->righttop > MAXNUM - 1) {//右栈为空
return NULL;
}
else {//右栈出栈
return (s->stack[s->righttop++]);
}
}
else {//参数错误
return NULL;
}
}
int main() {
dupsqstack *s;
int x, x1;
s=initDupStack();
for (int i = 0; i < 10; i++) {
pushDupStack(s, 'L', i + 1);//左栈入栈
pushDupStack(s, 'R', i + 10);//右栈入栈
}
printf("左栈的出栈顺序:\n");
while (s->lefttop != -1) {
x = popDupStack(s, 'L');
printf("%d ", x);
}
printf("\n右栈的出栈顺序:\n");
while (s->righttop != MAXNUM) {
x1 = popDupStack(s, 'R');
printf("%d ", x1);
}
system("pause");
return 0;
}
运行结果: