#include <stdio.h>
#include <malloc.h>
#define MaxSize 50
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];
int top1, top2;
} DStack;
//初始化共享栈
void InitStack(DStack *&s) {
s = (DStack *)malloc(sizeof(DStack));
s->top1 = -1;
s->top2 = MaxSize;
}
//销毁共享栈
void DestroyDStack(DStack *&s) {
free(s);
}
//判断栈是否为空
bool StackEmpty(DStack *s, int which) { //which指示需判断哪个栈是否为空
if (which == 1)
return (s->top1 == -1);
if (which == 2)
return (s->top2 == MaxSize);
}
//判断栈是否已满
bool StackFull(DStack *s) {
return (s->top1 == s-> top2 - 1);
}
//进栈
bool Push(DStack *&s, ElemType &e, int which) { //which指示取哪个栈的栈顶元素赋给e
if (s->top1 == s->top2 - 1)
return false;
if (which == 1)
s->top1++;
s->data[s->top1] = e;
if (which == 2)
s->top2--;
s->data[s->top2] = e;
}
//出栈
bool Pop(DStack *&s, ElemType &e, int which) { //which从哪个栈弹出栈顶元素赋给e
if (which == 1)
if (s->top1 == -1)
return false;
e = s->data[s->top1];
s->top1--;
return true;
if (which == 2)
if (s->top2 == MaxSize)
return false;
e = s->data[s->top2];
s->top2++;
return true;
}
//取栈顶元素
bool GetTop(DStack *s, ElemType &e, int which) { //which指示取哪个栈的栈顶元素赋给e
if (which == 1)
if (s->top1 == -1)
return false;
e = s->data[s->top1];
return true;
if (which == 2)
if (s->top2 == MaxSize)
return false;
e = s->data[s->top2];
return true;
}
//利用共享栈实现浏览器的前进与后退
//浏览一个新页面
bool Vist(DStack *&s, ElemType e) { //若栈已满,返回 false;否则返回 true
if (StackFull(s))
return false;
else {
Push(s, e, 1);
return true;
}
}
//后退浏览前一页面
bool Backward(DStack *&s, ElemType &e) { //若无法继续后退,返回 false;否则,将前一页面赋给 e,并且返回 true
if (StackFull(s) || s->top1 <= 0)
return false;
else {
Pop(s, e, 1);
Push(s, e, 2);
e = s->data[s->top1];
return true;
}
}
//前进浏览后一页面
bool Forward(DStack *&s, ElemType &e) { //若无法继续前进,返回 false;否则,将后一页面赋给 e,并且返回 true
if (StackEmpty(s, 1) || StackEmpty(s, 2))
return false;
else {
Pop(s, e, 2);
Push(s, e, 1);
e = s->data[s->top2];
return true;
}
}
int main() {
DStack s;
int i;
char e, a, b, c;
char num[3];
InitStack(s);
for (i = 0; i < 3; i++)
scanf("%c", num[i]);
for (i = 0; i < 3; i++)
Vist(s, num[i]);
Backward(s, c);
printf("%d", e);
Backward(s, b);
printf("%d", e);
Backward(s, a);
printf("%d", e);
return 0;
}
主函数只是编写了一部分,试着运行了一下,发现出问题了,然后找不到问题