题解 | #【模板】栈#C++手写栈实现
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include<iostream> #include<cstring> using namespace std; const int MAXN=100100; class mystack{ private: int a[MAXN]; int t=0;//the loction of top stack public: void push(int x); int pop(); int top(); bool empty(); }; void mystack::push(int x){ a[++t]=x; } int mystack::pop(){ int c=a[t]; t--; return c; } int mystack::top(){ return a[t]; } bool mystack::empty(){ if(t==0)return true; else return false; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0); int n; string s; mystack st; cin>>n; while(n--){ cin>>s; if(s=="push"){ int x; cin>>x; st.push(x); } else if(s=="pop"){ if(st.empty()) cout<<"error\n"; else cout<<st.pop()<<endl; } else{ //s=top if(st.empty()) cout<<"error\n"; else cout<<st.top()<<endl; } } return 0; }