【算法】堆栈模拟队列

相关题目: 7-22 堆栈模拟队列 (25分)

  1. 将两个堆栈编号为s1、s2 (将容量较小的栈编号为 s1)
  2. 用较小的栈作为临时存储栈(保证临时栈满时能完全移动到输出栈,即 s1 做临时栈)
    • Push 操作,将元素压入 s1
    • Pop 操作,在 s2 中取栈顶元素
    • 即临时栈负责进,输出栈负责出
  3. Push 操作
    • 若 s1 不满,则直接压入 s1
    • 若 s1 满且 s2 为空,则将 s1 中的元素全部移至 s2,将新元素压入 s1
    • 若 s1 满且 s2 不为空,则视栈满,即队列已满(ERROR: FULL)
  4. Pop 操作
    • 若 s2 不为空,则直接取 s2 的栈顶元素(Print *Top)
    • 若 s2 为空:
      • s1 为空,则表示队列为空,Pop 操作失败(ERROR: Empty)
      • s1 不为空,则将 s1 的全部元素移至 s2 ,取出 s2 的栈顶元素 (Print *Top)

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()

输入格式:

输入首先给出两个正整数N1N2,表示堆栈S1S2的最大容量。随后给出一系列的队列操作: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;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值