题解 | 【模板】栈的操作

【模板】栈的操作

https://www.nowcoder.com/practice/cdf02ea916454957b575585634e5773a

题干解读:要求对于栈中元素进行一系列操作

解题思路:利用cin的特性(遇到空格停止输入)使用字符串s输入字符串,然后根据字符串的不同执行不同操作.

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

int main() {
    int n;
    cin>>n;
    stack<int> t;
    for(int i=0;i<n;i++){
        string s;
        int temp;
        cin>>s;
        if(s == "push"){
            cin>>temp;
            t.push(temp);
        }else if(s == "pop"){
            if(t.empty()){
                cout<<"Empty"<<endl;
            }else{
                t.pop();
            }
        }else if(s == "size"){
            cout<<t.size()<<endl;
        }else if(s=="query"){
            if(t.empty()){
                cout<<"Empty"<<endl;
            }else{
                cout<<t.top()<<endl;
            }
        }



    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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