题解 | #堆栈的使用#

堆栈的使用

https://www.nowcoder.com/practice/e91982a145944ceab6bb9a4a508e0e26


//这个算法只能用于整数是一位数的情况,而题目里说  0 < n <= 10000

/*转到第19行
        string temp;///!!!!!!!!
        getline(cin,temp);//唉,这个错误折磨了我很久才发现。就是第一行数字后面有个换行符要接收一下才能正常地接收后续每一行地字符串,不然就默认接受的第一个字符串时数字后面的换行符

#include <iostream>
#include <stack>
using namespace std;

int main() {
    int n;
    while (cin >> n) {
    stack<char> num;
    while(!num.empty())num.pop();//C++没有提供可以调用的栈清空函数,要手动清空


        string temp;///!!!!!!!!
        getline(cin,temp);//唉,这个错误折磨了我很久才发现。就是第一行数字后面有个换行符要接收一下才能正常地接收后续每一行地字符串,不然就默认接受的第一个字符串时数字后面的换行符


        for(int i=1;i<=n;i++)
        {
            string str;
            getline(cin,str);//必须接受一行不能用cin>>str;
                if(str[0]=='A')
                {
                    if(num.empty())
                    {
                        cout<<"E"<<endl;
                    }
                    else
                    {
                        cout<<num.top()<<endl;
                    }

                }
                else if(str[0]=='P')
                {
                    num.push(str[2]);

                }
                else {
                    if(num.empty())continue;
                    else num.pop();
                }
        }

    }
}
*/


#include <iostream>
#include <stack>
using namespace std;

int main()
{
    int n;
    while (cin >> n)
    {
        stack<int> num;
        for(int i=1;i<=n;i++)
        {
            char x;
            int y;
            cin>>x;
            if(x=='A')
            {
                    if(num.empty())
                    {
                        cout<<"E"<<endl;
                    }
                    else
                    {
                        cout<<num.top()<<endl;
                    }
            }
            else if(x=='P')
                {
                    cin>>y;
                    num.push(y);

                }
            else
            {
                    if(num.empty())continue;
                    else num.pop();
            }
        }
    }
}







全部评论

相关推荐

点赞 评论 收藏
分享
是秃子总会发光_:科软的还被排序?不是大雪深埋吗
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-29 17:30
找实习找着找着就要进入7月了,马上秋招也要开始了,找实习还有意义吗?
绝迹的星:有面就面, 没面上就当日薪4位数大佬免费培训, 面上了再考虑要不要实习
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务