用数组模拟栈,只需要维护一个指针,因为栈的数据是单方向进入的,所以只需要维护一个指针。
stk[++head] = x;
head–
stk[head]
if(!head)
#include<iostream> using namespace std; const int N = 100010; int head,stk[N]; void push(int x) { stk[++head] = x; } void pop() { head--; } int query() { return stk[head]; } int isEmpty() { return head; } int main() { int n; cin>>n; while(n --) { string op; int x; cin >> op; if( op == "push") { cin>>x; push(x); }else if( op == "pop" ) { pop(); }else if(op == "empty") { if(!isEmpty())cout<<"Yes"<<endl; else cout<<"NO"<<endl; }else { cout<<query()<<endl; } } return 0; }