7-22 堆栈模拟队列 (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
题目理解:
利用两个堆栈模仿队列:
1.首先比较两个堆栈的大小,小的栈为输入栈,大的栈为输出栈。
2.如果输入栈满了,而输出栈为空,则将输入栈中所有元素全部转移到输出栈中(如果还有输入这时不能再转了!)。
3.如果输入栈满了,而输出栈不为空,则此时栈满(因此可以得知整个栈的最大容量为输入栈的两倍)。
下面输出:
4.输出栈不为空时,则输出栈的栈顶元素为队头元素。
5.输出栈为空,而输入栈不为空时,则将输入栈中的元素全部转入输出栈中,再输出栈顶元素。
6.如果输出栈和输入栈中的元素均为空时,则栈空。
#include<iostream>
#include<stack>
using namespace std;
#define ElementType int
typedef struct Stack{
stack<int> s1; //输入栈(小)
stack<int> s2; //输出栈(大)
int size1;
int size2;
};
Stack Sta;
int IsFull(Stack S);
int IsEmpty (Stack S);
void Push(Stack &S, ElementType item); //注意这里必须得用引用
ElementType Pop(Stack &S); //注意这里必须得用引用
int main()
{
int size1,size2;
cin>>size1>>size2;
//初始化
if(size1>size2)
{
Sta.size1 = size2;
Sta.size2 = size1;
}
else
{
Sta.size1 = size1;
Sta.size2 = size2;
}
char order;
while(1)
{
char order;
cin>>order;
if(order=='T')
break;
if(order=='A')
{
int data;
cin>>data;
if(IsFull(Sta))
cout<<"ERROR:Full"<<endl;
else
Push(Sta,data);
}
if(order=='D')
{
if(IsEmpty(Sta))
cout<<"ERROR:Empty"<<endl;
else
cout<<Pop(Sta)<<endl;
}
}
}
int IsFull(Stack S)
{
if(S.()==S.size1&&S.()!=0)
return 1;
else return 0;
}
int IsEmpty (Stack S)
{
if(S.()&&S.())
return 1;
else return 0;
}
void Push(Stack &S, ElementType item)
{
if(S.()<S.size1)
S.(item);
else
{
for(int i = 0;i<S.size1;i++)
{
S.(S.());
S.();
}
S.(item);
}
}
ElementType Pop(Stack &S)
{
if(!S.())
{
int ele = S.();
S.();
return ele;
}
else
{
for(int i = 0;i<S.size1;i++)
{
S.(S.());
S.();
}
int ele = S.();
S.();
return ele;
}
}