题解 | 【模板】栈

【模板】栈

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

//通过vector模拟即可,resize可以直接截取前面的数字舍弃末尾,剩下的直接简单输出就行
#include <iostream>
#include <vector>
#include <string>
using namespace std;

vector<int>res;
int n;

void push(int &val){
    res.emplace_back(val);
    return;
}
void pop(){
    if(!res.empty()){
        cout<<res.back()<<endl;
        res.resize(res.size()-1);
    }
    else cout<<"error"<<endl;
    return ;
}

void top(){
    if(!res.empty()){
        cout<<res.back()<<endl;
    }
    else cout<<"error"<<endl;
    return ;
}
int main() {
    int n;cin>>n;
    while(n--){
        string s;
        cin>>s;
        if(s=="push"){
            int val;
            cin>>val;
            push(val);
        }
        else if(s=="pop"){
            pop();
        }
        else top();
    }
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

用微笑面对困难:你出于礼貌叫了人一声大姐,大姐很欣慰,她真把你当老弟
点赞 评论 收藏
分享
10-22 19:44
门头沟学院 Java
面了100年面试不知...:那我得去剪个头
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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