题解 | #【模板】栈#

【模板】栈

https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf

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

int main() {
    int n ;
    cin >> n;
    stack<int> st;
    for (int i = 0;i < n;i++)
    {
        string op;
        getline(cin,op);
        auto it = op.find(' ');
        if (it != string::npos)
        {
            string a = op.substr(0,it);
            string data = op.substr(it + 1);
            if (a == "push")
            {
                st.push(stoi(data));
                //cout << st.top() << endl;
            }
        }
        else
        {
            if (op == "pop")
            {
                if (!st.empty())
                {
                    cout << st.top() << endl;
                    st.pop();
                }
                else
                {
                    cout << "error" << endl;
                }
            }
            else if (op == "top")
            {
                if (!st.empty())
                {
                    cout << st.top() << endl;
                }
                else
                {
                    cout << "error" << endl;
                }
            }
        }
        if(i == n - 1)
        {
            if (!st.empty())
            {
                cout << st.top() << endl;
            }
            else
            {
                cout << "error" << endl;
            }
        }
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

zYvv:双一流加大加粗再标红,然后广投。主要是获奖荣誉不够,建议开始不用追求大厂,去别的厂子刷下实习。
点赞 评论 收藏
分享
代码飞升:别用口语,后端就写后端,前端就写前端,最后别光后悔
点赞 评论 收藏
分享
哈哈哈哈哈哈哈哈哈哈这个世界太美好了
凉风落木楚山秋:毕业出路老师不管,你盖个章他好交差就完事了,等你盖完毕业了就不关他事情了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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