基础实验3-2.5 堆栈模拟队列 (25分)
设已知有两个堆栈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
这道题比较特殊的地方就是:如果用大杯子进行入栈,小的杯子进行倒出,会出现大杯子底下残留一个。如果残留多个需要小杯子入,大杯子出;
只残留一个时:那么在输出的时候,需要把大杯中的前两个倒入小杯子中,再输出大杯子残留的这个,再输出小杯子中的。
#include<iostream>
#include<stack>
using namespace std;
int main(){
int N1,N2;
cin>>N1>>N2;
if(N1<N2){
int temp=N2;
N2=N1;
N1=temp;
}
char ch;
int num;
stack<int>st1,st2;
while(1){
cin>>ch;
if(ch=='T'){
exit(0);
}else if(ch=='A'){
cin>>num;
if(st1.size()<N1){
st1.push(num);
cout<<"check001:"<<st1.top()<<endl;
}else
cout<<"error:full"<<endl;
}else if(ch=='D'){
if(st1.size()==N1){
while(st2.size()<N2){
st2.push(st1.top());
cout<<"check002:"<<st2.top()<<endl;
st1.pop();
}
cout<<"check003:"<<st1.top()<<endl;
st1.pop();
}
else if(st1.empty()&&st2.empty()){
cout<<"error:empty"<<endl;
continue;
}
else{
cout<<"check004:"<<st2.top()<<endl;
st2.pop();
}
}
}
return 0;
}
比较常用的方式是:用小的容量进行入栈操作,大的容量进行出栈操作,这样两个栈的用的容量相等,那么进行倒出和打印的操作就可以实现队列的操作。
代码中的check只是为了检查程序。
#include<iostream>
#include<stack>
using namespace std;
int main(){
stack<int>s1,s2;
int n1,n2;
cin>>n1>>n2;
if(n1>n2){
int temp=n1;
n1=n2;
n2=temp;
}
char ch;
int num;
while(1){
cin>>ch;
if(ch=='T'){
exit(0);
}else if(ch=='A'){
cin>>num;
if(s1.size()==n1){
if(s2.size()==0){
while(s1.size()){
cout<<"check001:"<<s1.top()<<endl;
s2.push(s1.top());
s1.pop();
}
s1.push(num);
cout<<"check002:"<<s1.top()<<endl;
}
else{
cout<<"error:full"<<endl;
continue;
}
}else{
s1.push(num);
cout<<"check003:"<<s1.top()<<endl;
}
}else if(ch=='D'){
if(s2.size()==0){
if(s1.size()==0){
cout<<"error:empty"<<endl;
continue;
}else
while(s1.size()){
s2.push(s1.top());
s1.pop();
}
}
cout<<s2.top()<<endl;
s2.pop();
cout<<"check004:"<<s1.size()<<" "<<s2.size()<<endl;
}
}
return 0;
}