题解 | 【模板】栈

#include <iostream>
using namespace std;

const int N = 1e5 + 5;

class stack{
    private:
        int s[N];
        int top_index = 0;
    public:
        void push(int x){
            s[top_index] = x;            
            top_index += 1;
        }
        void pop(){
            if(top_index > 0){
                top_index --;
                cout << s[top_index] << endl;
            }
            else{
                cout << "error" << endl;
            }
        }
        void top(){
            if(top_index > 0){
                cout << s[top_index-1] << endl;
            }
            else{
                cout << "error" << endl;
            }
        }
};

int main() {
    stack s;
    int n, x;
    string op;
    cin >> n;
    for(int i = 0; i<n; i++){
        cin >> op;
        if(op=="push"){
            cin >> x;
            s.push(x);
        }
        else if(op=="pop"){
            s.pop();
        }
        else if(op=="top"){
            s.top();
        }
    }
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

06-12 16:23
已编辑
小米_软件开发(准入职员工)
点赞 评论 收藏
分享
字节一直是我的白月光,考虑到转正还是拒了日常实习。
从明天开始狠狠卷JV...:为什么你释放的offer没流到我头上
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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