问题:
利用两个栈S1,S2来模拟一个队列。
栈基本操作如下:
Push(S,x); // 入栈操作
Pop(S,x); // 出栈操作
StackEmpty(S); // 判断栈是否为空
StackOverflow(S); // 判断栈是否满
利用栈的运算来实现该队列的3个运算:
- Enqueue – 入队操作
- Dequeue – 出队操作
- QueueEmpty – 判空操作
算法思想:
入队时,先入栈S1(此时为逆序),出队时,先将S1的元素出栈再入栈到S2中(此时为顺序),再出栈。如果S1和S2都为空则队列为空
算法实现
入队操作
bool Enqueue(Stack *S1, Stack *S2, ElemType e){
if(!StackOverflow(S1)){ //S1不满,入栈
Push(S1, e);
return true;
}
if(StackOverflow(S1) && !StackEmpty(S2)){ //S1满栈,S2不空则无法入队
return false;
}
if(StackOverflow(S1) && StackEmpty(S2)){ //如果S1满,S2空
while(!StackEmpty(S1)){ //S1不空,出栈,S2入栈
Pop(S1, x);
Push(S2, x);
}
}
Push(S1, e);
return true;
}
出队操作
bool Dequeue(Stack *S1, Stack *S2, ElemType x){
if(!StackEmpty(S2)){ //S2不为空,出栈
Pop(S2, x);
return true;
}else{
return false;
}
if(StackOverflow(S1)){ //S1栈满时,出栈,S2入栈
Pop(S1, x);
Push(S2, x);
}
Pop(S2, x);
return true;
}
判空操作
bool QueueEmpty(Stack S1, Stack S2){
if(StackEmpty(S1) && StackEmpty(S2)){ //S1,S2都不为空
return true;
}
return false;
}