--- title: "栈" created: 2025-11-28 tags: - 算法 --- # 栈 ## 题目 [模拟栈](https://www.acwing.com/problem/content/830/) ![[image-50928953.png]] ## 思路分析 以0为起始位开始存 只在一端操作(仅用一个指针/下标维护当前可用位置) 用-1判空 ## 代码实现 ```cpp #include using namespace std; const int N = 100010; int st[N]; int top = -1; int n; int main() { cin >> n; while(n--) { string s; cin >> s; //栈顶所在索引往后移动一格,然后放入x。 if(s == "push") { int a; cin >> a; st[++top] = a; } //往前移动一格 if(s == "pop") { top --; } //返回栈顶元素 if(s == "query") { cout << st[top] << endl; } //大于等于 0 栈非空,小于 0 栈空 if(s == "empty") { cout << (top == -1 ? "YES" : "NO") << endl; } } return 0; } ``` ## 同类题型 ## 视频讲解 --- ⬅️ [[栈与队列|栈与队列]] 🏠 [[00-听课板子]] ➡️ [[2-Learning/02-算法/02-听课板子/数据结构/栈与队列/队列|队列]]