相关题目: 7-22 堆栈模拟队列 (25分)
- 将两个堆栈编号为s1、s2 (将容量较小的栈编号为 s1)
- 用较小的栈作为临时存储栈(保证临时栈满时能完全移动到输出栈,即 s1 做临时栈)
Push
操作,将元素压入 s1Pop
操作,在 s2 中取栈顶元素- 即临时栈负责进,输出栈负责出
Push
操作- 若 s1 不满,则直接压入 s1
- 若 s1 满且 s2 为空,则将 s1 中的元素全部移至 s2,将新元素压入 s1
- 若 s1 满且 s2 不为空,则视栈满,即队列已满(ERROR: FULL)
Pop
操作- 若 s2 不为空,则直接取 s2 的栈顶元素(Print *Top)
- 若 s2 为空:
- s1 为空,则表示队列为空,
Pop
操作失败(ERROR: Empty) - s1 不为空,则将 s1 的全部元素移至 s2 ,取出 s2 的栈顶元素 (Print *Top)
- s1 为空,则表示队列为空,
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
根据以上描述写出代码:
#include <bits/stdc++.h>
using namespace std;
void move(stack<int> &s1, stack<int> &s2) {
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
}
int main() {
int n1, n2, x;
scanf("%d%d", &n1, &n2);
if (n1 > n2) swap(n1, n2);
getchar();
stack<int> s1, s2;
char op;
while (op = getchar(), op != 'T') {
if (op == 'A') {
scanf(" %d ", &x);
if (s1.size() < n1) s1.push(x);
else if (s2.size() != 0) printf("ERROR:Full\n");
else {
move(s1, s2);
s1.push(x);
}
} else {
getchar(); // 接收后一个空格
if (!s2.empty()) {
printf("%d\n", s2.top());
s2.pop();
} else if (s1.empty()) {
printf("ERROR:Empty\n");
} else {
move(s1, s2);
printf("%d\n", s2.top());
s2.pop();
}
}
}
return 0;
}