3-08. 堆栈模拟队列(25)
时间限制
400 ms
内存限制
32000 kB
代码长度限制
8000 B
判题程序
Standard
设已知有两个堆栈S1和S2,请用这两个堆栈模拟出一个队列Q。
所谓用堆栈模拟队列,实际上就是通过调用堆栈的下列操作函数:
(1) int IsFull(Stack S):判断堆栈S是否已满,返回1或0;
(2) int IsEmpty (Stack S ):判断堆栈S是否为空,返回1或0;
(3) void Push(Stack S, ElementType item ):将元素item压入堆栈S;
(4) 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行。
样例输入与输出:
序号 | 输入 | 输出 |
1 |
2 2 A 1 A 2 D D T |
1 2 |
2 |
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<stdio.h>
#include<stack>
using namespace std;
/*
首先要弄清楚逻辑,然后要切记,每次入栈,出栈,栈数据倒入,都要更新容量
*/
int main()
{
stack<int> sStack; //容量小的栈,用于处理入队
stack<int> bStack; //容量大的栈,用于处理出队
int small,big,sCount=0,bCount=0; //两个栈的容量以及容量计数
scanf("%d%d",&small,&big);
if(small>big)
{
int temp=small;
small=big;
big=small;
}
char op;
int num;
while(true)
{
scanf("%c",&op);
if(op=='T')
break;
if(op=='A') //入队
{
scanf("%d",&num);
if(sCount<small)
{
sStack.push(num);
//printf("把%d压入sStack\n",sStack.top());
sCount++; //sStack容量加1
}
else if(sCount==small && bCount==0) //若sStack已满,bStack为空,将sStack的数压入bStack; 再将num压入sStack
{
while(!sStack.empty())
{
//printf("把%d从sStack压入bStack\n",sStack.top());
bStack.push(sStack.top());
sStack.pop();
}
sStack.push(num);
//printf("把%d压入sStack\n",sStack.top());
bCount=sCount; //更新栈的容量
sCount=1;
}
else
printf("ERROR:Full\n");
}
else if(op=='D') //出队
{
if(bCount!=0)
{
printf("%d\n",bStack.top());
bStack.pop();
bCount--; //bStack容量减1
}
else if(bCount==0 &&sCount>0) //若sStack非空,bStack为空,将sStack的数压入bStack
{
while(!sStack.empty())
{
bStack.push(sStack.top());
sStack.pop();
}
printf("%d\n",bStack.top());
bStack.pop();
bCount=sCount-1; //更新栈的容量
sCount=0;
}
else
printf("ERROR:Empty\n");
}
}
return 0;
}