题干解读:要求对于栈中元素进行一系列操作
解题思路:利用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;
}
}
}
}

京公网安备 11010502036488号