题解 | 【模板】栈

#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")

全部评论

相关推荐

02-08 15:53
门头沟学院 Java
CoderEcho:让公司知道便宜没好货
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务