堆栈的使用

这是一个C++程序,主要使用栈数据结构处理字符输入。程序读取整数n,然后根据输入的字符'A'、'P'或'O'进行不同操作:'A'查询栈顶元素,'P'压栈,'O'弹栈。在读取字符前,通过getchar()排除换行符干扰。该程序展示了基本的输入处理和栈操作技巧。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <string>
#include <cstdio>
#include <stack>
#include <vector>
using namespace std;
int main(){
    int n;
    while(scanf("%d",&n)!=EOF){
        if (n == 0) break;
        char a;
        stack<int> sta;
        for(int i = 0;i < n; i++){
            getchar();
            scanf("%c",&a);//这边为什么会把换行当字符输入 才加个getchar() 或者用 cin >>a
            if(a=='A'){
                if(sta.empty()){
                    printf("E\n");
                }else{
                    printf("%d\n",sta.top());
                }
            }else if(a == 'P'){
                int b;
                scanf("%d",&b);
                sta.push(b);
            }else if(a == 'O'){
                if(!sta.empty()){
                    sta.pop();
                }
            }
        }
        printf("\n");
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值