设已知有两个堆栈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
c++版
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[])
{
int n, m;
cin>>n>>m;
int len = min(n, m);
stack<int> stk_in, stk_out;
char ch;
while(cin>>ch, ch != 'T'){
if(ch == 'A'){
cin>>n;
if(stk_in.size() < len)
stk_in.push(n);
else if(stk_in.size() == len && stk_out.size() == 0){
for(int i = 0; i < len; i++){
stk_out.push(stk_in.top());
stk_in.pop();
}
stk_in.push(n);
}
else
cout<<"ERROR:Full"<<endl;
}else{
if(!stk_out.empty())
cout<<stk_out.top()<<'\n',stk_out.pop();
else if(!stk_in.empty()){
while(!stk_in.empty()){
stk_out.push(stk_in.top());
stk_in.pop();
}
cout<<stk_out.top()<<'\n',stk_out.pop();
}else
cout<<"ERROR:Empty"<<endl;
}
}
return 0;
}
Python版
n, m = map(int, input().split())
l = list(input().split())
i, n = 0, min(n, m)
stk_in = [];stk_out = []; ans = []
while i < len(l) - 1:
if l[i] == 'A':
i += 1
if len(stk_in) < n:
stk_in.append(l[i])
elif len(stk_in) == n and not stk_out:
while stk_in:
stk_out.append(stk_in.pop())
stk_in.append(l[i])
else:
ans.append("ERROR:Full")
else:
if stk_out:
ans.append(stk_out.pop())
elif stk_in:
while stk_in:
stk_out.append(stk_in.pop())
ans.append(stk_out.pop())
else:
ans.append("ERROR:Empty")
i += 1
print(*ans, sep="\n")