设已知有两个堆栈S1和S2,请用这两个堆栈模拟出一个队列Q。
所谓用堆栈模拟队列,实际上就是通过调用堆栈的下列操作函数:
int IsFull(Stack S):判断堆栈S是否已满,返回1或0;
int IsEmpty (Stack S ):判断堆栈S是否为空,返回1或0;
void Push(Stack S, ElementType item ):将元素item压入堆栈S;
ElementType Pop(Stack S ):删除并返回S的栈顶元素。
实现队列的操作,即入队void AddQ(ElementType item)和出队ElementType DeleteQ()。
输入格式:
输入首先给出两个正整数N1和N2,表示堆栈S1和S2的最大容量。随后给出一系列的队列操作:A item表示将item入列(这里假设item为整型数字);D表示出队操作;T表示输入结束。
输出格式:
对输入中的每个D操作,输出相应出队的数字,或者错误信息ERROR:Empty。如果入队操作无法执行,也需要输出ERROR:Full。每个输出占1行。
输入样例:
3 2
A 1 A 2 A 3 A 4 A 5 D A 6 D A 7 D A 8 D D D D T
输出样例:
ERROR:Full
1
ERROR:Full
2
3
4
7
8
ERROR:Empty
作者
DS课程组
单位
浙江大学
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
左边为小杯用来入队,右边为大杯用来出队
显然左边满右边非空为队列满,左右都空为栈空
当左边满右边空需要入队或者右边空需要出队时,需要左边元素依次出栈并进入右边
#include <bits/stdc++.h>
using namespace std;
stack<int> s1,s2; //s1为大杯,s2为小杯
int n,m; //n为大杯,m为小杯
int judge(){
if(s1.size()!=0&&s2.size()==m) return 1;
else return 0;
}
void Push(int i){
if(s2.size()==m){
while(!s2.empty()){
int j=s2.top();
s2.pop();
s1.push(j);
}
s2.push(i);
}
else s2.push(i);
}
int emp(){
if(s1.size()==0&&s2.size()==0) return 1;
else return 0;
}
int Pop(){
if(s1.empty()){
while(!s2.empty()){
int j=s2.top();
s2.pop();
s1.push(j);
}
}
int t=s1.top();
s1.pop();
return t;
}
int main(){
cin>>n>>m;
if(n<m) swap(n,m);
char ch;
getchar();
while(cin>>ch&&ch!='T'){
if(ch=='A'){
int i;
cin>>i;
if(judge()==1){
cout<<"ERROR:Full"<<endl;
}
else Push(i);
}
else if(ch=='D'){
if(emp()==1){
cout<<"ERROR:Empty"<<endl;
}
else{
int t=Pop();
cout<<t<<endl;
}
}
}
}