笔记:
栈可以理解为“吃了吐”,也就是指元素从顶端进入这个数据结构之后,会从顶端再出去。(表述的不太好。。。)
用数组&指针可以模拟这个数据结构。
push操作:把指针上移一位,在数组中指针所指的位置加入这个元素。
pop操作:把指针下移一位。
query操作(询问栈顶元素):返回指针所指位置的元素即可。
empty操作(询问是否为空):若指针指向空(相当于指向栈底)那么就是栈空,否则不为空。
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1000001;
int stk[N], top;
string empty() {
if (top == 0) return "YES";
return "NO";
}
int main() {
int t; cin>>t;
while ( t--) {
string op; int x;
cin>>op;
if (op == "push") {
cin>>x;
stk[++top] = x;
}
else if (op == "pop") top--;
else if (op == "query") cout<<stk[top]<<endl;
else cout<<empty()<<endl;
}
}
《吃了吐》
不要在我吃东西的时候讲这个词
azzz