题解 | #堆栈的使用#

堆栈的使用

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







全部评论

相关推荐

找到实习了&nbsp;给了150一天&nbsp;但是说是低代码&nbsp;值得去吗
码农索隆:是在没实习,可去,待个一两周,不行就润呗
点赞 评论 收藏
分享
07-03 11:02
中山大学 C++
字节刚oc,但距离九月秋招很近了有两段互联网实习,非腾讯字节。不敢赌转正,现在在纠结去还是不去如果实习俩月离职会有什么后果吗
阿城我会做到的:不去后悔一辈子,能否转正取决于ld的态度,只要他不卡,答辩就是走流程,个人觉得可以冲一把
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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