AB1 【模板】栈
tt == 0 代表栈是空的(判断栈空方便),tt 为指向栈顶的“指针”; push x, 往栈顶插入x; pop 栈不空就可以弹出,弹出的时候,还要输出该数; top 栈不空就可以获得栈顶元素,记得输出该数;
#include <bits/stdc++.h>
using namespace std;
// 模拟栈,0就代表栈空
const int N = 1e6 + 10;
int stk[N];
int tt;
void pushOP(int k) {
stk[++tt] = k;
return ;
}
bool isEmpty() {
// 若 tt <= 0则栈为空
if (tt <= 0) return true;
else return false;
}
void popOP() {
// if (isEmpty()) return;
// else --tt;
--tt; // 主程序会进行判断,这样是会保证操作有意义的
}
int getTop() {
return stk[tt];
}
string op; // 待输入的操作
int m;
int main() {
cin >> m;
int x;
while (m--) {
cin >> op;
if (op == "push") {
cin >> x;
pushOP(x);
}else if (op == "pop") {
if (isEmpty()) cout << "error" << endl;
else {
int k = getTop();
popOP();
cout << k << endl;
}
}else {
if (isEmpty()) cout << "error" << endl;
else cout << getTop() << endl;
}
}
return 0;
}
AB2 栈的压入、弹出序列
关键思路:辅助栈模拟,具体思路模拟在代码中;
class Solution {
public:
// 解题思路:利用一个辅助栈来模拟
// 1. 栈是先入后出结构
// 2. 本题判断这个弹出序列是否可行,那么要想能弹出就得先入栈
// 3. 那么我们就用两个指针分别指向这两个序列,i指针指向pushV,j指针指向popV
// - 首先若当前两个指针指向的元素相等,说明这个元素是放入栈后立马弹出的,就得++i, ++j一起移动
// - 若二者不相等,就将这个pushV[i],放入辅助栈中(模拟出栈,看能否和出栈序列匹配),且++i
//重复比较过程,大致思路是这样,可以动手模拟,并且写一下代码试一下
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
// 用自带的stl栈来做辅助栈
stack<int> stk;
// 初始化两个指针的位置
int i = 0;
int j = 0;
int lenPushV = pushV.size();
while (i < lenPushV) { // 当i指针还没有走到头
if (pushV[i] != popV[j]) {
stk.push(pushV[i++]); // 按照这个序列把元素放入辅助栈中,且i要往后走
}else {
++i;
++j;
// 若辅助栈不空,且当前辅助栈顶元素和当前j指针指向的弹出序列中的元素相等,就说明是这个序列
// 就得弹出辅助栈栈顶元素,且j指针要继续往后遍历
while (!stk.empty() && stk.top() == popV[j]) {
stk.pop();
++j;
}
}
}
// 最终,只有辅助栈为空,就说明这个弹出序列是正确的,辅助栈中还有元素,就说明这个序列有问题
return stk.empty();
}
};