7-22 堆栈模拟队列 (25分)

本文介绍了一种使用两个堆栈模拟队列操作的方法,包括入队和出队的实现。通过C++代码示例,详细展示了如何在有限制的条件下进行数据的入队和出队操作,以及在队列满或空时的错误处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

7-22 堆栈模拟队列 (25分)

AC代码

#include <iostream>
#include <cstdio>
#include <stack>
#include <algorithm>
using namespace std;
stack<int> s1, s2;
int main(){
    int m, n, num;
    scanf("%d%d", &m, &n);
    if (m > n) swap(m, n);
    char ch;
    getchar();
    while (scanf("%c", &ch) && ch != 'T'){
        if (ch == ' ') continue;
        if (ch == 'A'){
            scanf("%d", &num);
            if (s1.size() < m) s1.push(num);
            else if (s1.size() == m){
                if (s2.empty()){
                    while (!s1.empty()){
                        s2.push(s1.top());
                        s1.pop();
                    }
                    s1.push(num);
                }
                else printf("ERROR:Full\n");
            }
        }
        else {
            if (!s2.empty()){
                printf("%d\n", s2.top());
                s2.pop();
            }
            else if (!s1.empty()){
                while (!s1.empty()){
                    s2.push(s1.top());
                    s1.pop();
                }
                printf("%d\n", s2.top());
                s2.pop();
            }
            else printf("ERROR:Empty\n");
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值