第一个栈负责进队,第二个负责出队
用两个栈模拟队列
#include<stdio.h>
#define maxsize 10
typedef struct s {
int data[maxsize];
int top;
}SqStack;
int InitStack(SqStack& S1) {
S1.top = -1;
return 1;
}
int push(SqStack& S, int x) {
S.data[++S.top] = x;
return 1;
}
int pop(SqStack& S, int& x) {
x = S.data[S.top--];
return 1;
}
int isEmpty(SqStack S) {
if (S.top == -1) {
return 1;
}
else
{
return 0;
}
}
int isOverFlow(SqStack S) {
if (S.top == maxsize - 1) {
return 1;
}
else
{
return 0;
}
}
int EnQueue(SqStack& S1, SqStack& S2,int x) {
if (isOverFlow(S1)&&!isEmpty(S2)) {
printf("栈满");
return 0;
}
int e;
if (isOverFlow(S1) && isEmpty(S2)) {
while (!isEmpty(S1)) {
pop(S1, e);
push(S2,e);
}
push(S1, x);
return 1;
}
if (!isOverFlow(S1)) {
push(S1, x);
}
}
void DeQueue(SqStack& S1, SqStack& S2, int &x) {
int e;
if (!isEmpty(S2)) {
pop(S2, x);
}else if (!isEmpty(S1) && isEmpty(S2)) {
while (!isEmpty(S1)) {
pop(S1,e);
push(S2,e);
}
pop(S2, x);
}
else if(isEmpty(S1) && isEmpty(S2)) {
printf("队空");
}
}
int EisEmpty(SqStack S1,SqStack S2) {
if (isEmpty(S1) && isEmpty(S2)) {
return 1;
}
else {
return 0;
}
}
int main() {
SqStack S1;
SqStack S2;
InitStack(S1);
InitStack(S2);
int e;
EnQueue(S1, S2, 8);
EnQueue(S1, S2, 5);
EnQueue(S1, S2, 7);
DeQueue(S1, S2, e);
printf("%d", e);
DeQueue(S1, S2, e);
printf("%d", e);
DeQueue(S1, S2, e);
printf("%d ", e);
printf("%d", EisEmpty(S1, S2));
}