栈的常用操作
2023-08-16 13:55:14
发布于:浙江
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <cmath>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N=1e5+5;
int m,n;
stack<int> st;
int main(){
cin >> n;
while(n--){
string s;
cin >> s;
if(s == "push"){
cin >> m;
st.push(m);
}else if(s == "pop"){
if(st.empty()){
cout << "pop fail"<<endl;
}else{
cout << "pop " << st.top()<<endl;
st.pop();
}
}else if(s == "top"){
if(st.empty()){
cout <<"top fail"<<endl;
}else{
cout << "top = " << st.top() << endl;
}
}else if(s == "size"){
cout << st.size() << endl;
}else{
if(st.empty()) {
cout << "yes" << endl;
}else{
cout << "no" << endl;
}
}
}
return 0;
}
//栈 stack<int>st 后进先出的容器
//
//st.push(x);//存入数据
//st.size();//访问栈中元素数量
//st.empty();//判断栈中是否为空
//st.pop();//弹出栈顶元素 (必须先判断栈中不为空)
//st.top();//访问栈顶元素 (必须先判断栈中不为空)
//while(!st.empty()) st.pop();//清空栈中元素
全部评论 2
炫总一口炫一个小孩
2024-02-02 来自 北京
1炫总衰死辣!!!
2024-02-02 来自 北京
1
有帮助,赞一个