题型与套路:栈和队列
这一课复习栈和队列最常考的三类题:判断出栈序列是否合法、用两个栈实现队列、用单调栈求下一个更大的数,先手写,再用 std::stack 写。
栈和队列本身不难,难的是看出一道题该用哪个、怎么用。这一课的三类题(外加循环队列的计算题)在期末、考研 408 和面试里反复出现,每类记住一个套路。
套路一:出栈序列合不合法
第一课手算过:入栈顺序 1 2 3,出栈顺序 3 1 2 不可能。写成程序就是照着做一遍:按顺序 push,每 push 一个,就看栈顶是不是下一个该出的,是就一直 pop。最后栈空了,说明这个出栈顺序做得到。
栈
1231#include <iostream>2#include <vector>3using namespace std;4 5// 入栈顺序是 1, 2, …, n;out 是想要的出栈顺序6bool valid(const vector<int>& out) {7 int n = out.size();8 int st[100], t = -1, k = 0;9 for (int x = 1; x <= n; x++) {10 st[++t] = x;11 while (t >= 0 && st[t] == out[k]) {12 t--;13 k++;14 }15 }16 return t == -1;17}18 19int main() {20 vector<vector<int>> tests = {{3, 2, 1}, {3, 1, 2}, {2, 4, 3, 1}, {4, 1, 2, 3}};21 for (const vector<int>& p : tests) {22 for (int x : p)23 cout << x << " ";24 cout << (valid(p) ? "可以" : "不行") << "\n";25 }26 return 0;27}
3 2 1 可以 3 1 2 不行 2 4 3 1 可以 4 1 2 3 不行
每个数最多进一次、出一次:O(n)。
入栈顺序是 1 2 3 4 5,哪一个不可能是出栈顺序?
判断出栈序列
✓补全 valid:入栈顺序是 1 到 n,判断 out 能不能是出栈顺序。
1 0 1
1#include <iostream>2#include <vector>3using namespace std;4 5bool valid(const vector<int>& out) {6 int n = out.size();7 int st[100], t = -1, k = 0;8 for (int x = 1; x <= n; x++) {9 // push x;栈顶等于 out[k] 就一直 pop,k++10 }11 return t == -1;12}13 14int main() {15 cout << valid({1, 3, 2}) << " " << valid({3, 1, 2}) << " " << valid({4, 3, 5, 2, 1}) << "\n";16 return 0;17}
套路二:两个栈做一个队列
面试常问:只有栈,怎么做出先进先出?用两个:in 只管进,out 只管出。出队时 out 空了,就把 in 里的全部倒进 out:顺序一倒,最早进来的正好到了 out 的栈顶。
in
123out
3211#include <iostream>2using namespace std;3 4class TwoStackQueue {5 int in[100], out[100];6 int tin = -1, tout = -1; // 两个栈的栈顶下标7public:8 void enqueue(int x) {9 in[++tin] = x;10 }11 int dequeue() {12 if (tout == -1) // out 空了才倒13 while (tin >= 0)14 out[++tout] = in[tin--];15 return out[tout--];16 }17};18 19int main() {20 TwoStackQueue q;21 q.enqueue(1);22 q.enqueue(2);23 q.enqueue(3);24 cout << q.dequeue() << " ";25 q.enqueue(4);26 cout << q.dequeue() << " ";27 cout << q.dequeue() << " ";28 cout << q.dequeue() << "\n";29 return 0;30}
1 2 3 4
关键是只在 out 空的时候才倒:out 里还有东西就倒,新来的会压在老的上面,顺序就乱了。每个元素一辈子只被倒一次,所以虽然某次出队可能要倒很多个,平均下来每次是 O(1)(均摊,和 vector 容量翻倍是一个道理)。
in 里从栈底到栈顶是 1 2 3,out 是空的。出队一次以后,out 里从栈底到栈顶是什么?
两个栈做队列
✓补全 pop:out 空了才把 in 全部倒过去,再从 out 出。
5 6 7
1#include <iostream>2#include <stack>3using namespace std;4 5class MyQueue {6 stack<int> in, out;7public:8 void push(int x) { in.push(x); }9 int pop() {10 // out 空:把 in 一个个取出来 push 进 out11 if (out.empty()) return -1; // 倒过以后还是空,才说明队列空了12 int x = out.top();13 out.pop();14 return x;15 }16};17 18int main() {19 MyQueue q;20 q.push(5);21 q.push(6);22 cout << q.pop() << " ";23 q.push(7);24 cout << q.pop() << " ";25 cout << q.pop() << "\n";26 return 0;27}
套路三:单调栈,下一个更大的数
题目:对每个数,找它右边第一个比它大的数,没有就是 −1。两层循环是 O(n²)。套路是单调栈:栈里放还没找到答案的数的下标,它们从栈底到栈顶是递减的。来了一个新数,比栈顶大,栈顶的答案就是它,pop;一直到栈顶不比它小,再把它 push。
i1#include <iostream>2using namespace std;3 4int main() {5 int a[] = {2, 1, 5, 3, 4}, n = 5;6 int ans[5], st[5], t = -1;7 for (int i = 0; i < n; i++) {8 while (t >= 0 && a[i] > a[st[t]])9 ans[st[t--]] = a[i]; // 栈顶等到了10 st[++t] = i;11 }12 while (t >= 0)13 ans[st[t--]] = -1; // 一直没等到14 for (int i = 0; i < n; i++)15 cout << ans[i] << " ";16 cout << "\n";17 return 0;18}
5 5 -1 4 -1
每个下标进栈一次、出栈一次:O(n)。「下一个更大 / 更小」「每日温度」「柱状图里最大的矩形」都是这个套路。
a = 3 1 4 2,每个数「右边第一个比它大的数」依次是什么(没有就是 −1)?
下一个更小的数
✓和课上相反:对每个数找右边第一个比它小的数,没有就是 −1。用 vector<int> 当单调栈。
3 3 1 1 -1
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> a = {4, 6, 3, 5, 1};7 int n = a.size();8 vector<int> ans(n, -1), st;9 for (int i = 0; i < n; i++) {10 // 新数比栈顶小:栈顶的答案就是它,pop11 st.push_back(i);12 }13 for (int x : ans)14 cout << x << " ";15 cout << "\n";16 return 0;17}
循环队列的计算题
考试会换着花样定义 rear。先看清楚 rear 指的是队尾元素还是下一个空位,公式跟着变:
| rear 指着 | 长度 | 队满 |
|---|---|---|
| 下一个空位(这门课的写法) | (rear - front + MAX) % MAX | (rear + 1) % MAX == front |
| 队尾元素本身 | (rear - front + 1 + MAX) % MAX | (rear + 2) % MAX == front |
考试常考: 「用数组 A[0..n] 实现循环队列」说的是 n + 1 个格子,MAX = n + 1,别当成 n。
MAX = 10 的循环队列,这次 rear 指着队尾元素本身。front = 7,rear = 2,队里有几个?
用 STL 写
面试里这三个套路都不手写数组。单调栈最常用 vector<int> 当栈:push_back、back、pop_back,和 stack<int> 一样是 O(1),还能随时看栈里所有的下标。下面是「每日温度」:每天要等几天才会更暖和,答案是下标的差,这就是栈里放下标、不放值的原因。
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> temp = {73, 74, 75, 71, 69, 72, 76, 73};7 int n = temp.size();8 vector<int> wait(n, 0); // 一直等不到就是 09 vector<int> st; // 当栈用:存下标10 for (int i = 0; i < n; i++) {11 while (!st.empty() && temp[i] > temp[st.back()]) {12 wait[st.back()] = i - st.back();13 st.pop_back();14 }15 st.push_back(i);16 }17 for (int w : wait)18 cout << w << " ";19 cout << "\n";20 return 0;21}
1 1 4 2 1 1 0 0
两个栈做队列换成两个 stack<int>,再数一数一共倒了多少个元素:
1#include <iostream>2#include <stack>3using namespace std;4 5class MyQueue {6 stack<int> in, out;7public:8 int moves = 0; // 一共倒了几个元素9 void push(int x) { in.push(x); }10 int pop() {11 if (out.empty())12 while (!in.empty()) {13 out.push(in.top());14 in.pop();15 moves++;16 }17 int x = out.top();18 out.pop();19 return x;20 }21};22 23int main() {24 MyQueue q;25 int pops = 0, last = 0;26 for (int i = 1; i <= 1000; i++) {27 q.push(i);28 if (i % 3 == 0) {29 last = q.pop();30 pops++;31 }32 }33 cout << pops << " 次出队,最后出来的是 " << last << ",一共倒了 " << q.moves << " 个\n";34 return 0;35}
333 次出队,最后出来的是 333,一共倒了 363 个
333 次出队一共只倒了 363 个元素,平均每次一个多一点:这就是均摊 O(1)。每个元素最多被倒一次,倒的总数不会超过入队的总数。
| 套路 | 用什么 | 每个元素 | 一共 |
|---|---|---|---|
| 出栈序列 | stack<int> 或数组 | 进一次、出一次 | O(n) |
| 两个栈做队列 | 两个 stack<int> | 最多倒一次 | 每次均摊 O(1) |
| 单调栈 | vector<int> 存下标 | 进一次、出一次 | O(n) |
面试里: 看到「右边(左边)第一个更大 / 更小」就想单调栈,栈里放下标;「用栈实现队列」考的是只在 out 空时才倒,以及均摊分析;反过来「用队列实现栈」是每次 push 后把前面的元素绕到队尾,push 变成 O(n)。真写代码要先进先出时,直接用 queue<int> 或 deque<int>。
用两个 stack<int> 做的 MyQueue:push 1、2、3,pop,push 4、5,pop,pop,pop。moves(一共倒了几个元素)最后是几?
小结
栈和队列三个套路
- 出栈序列:照着 push,栈顶该出就 pop,最后栈空才合法
- 两个栈做队列:out 空了才把 in 倒过去,均摊 O(1)
- 单调栈:栈里放等答案的下标,新数一来先结算比它小的
- STL:stack / queue 是 deque 外面的一层;单调栈常用 vector
1while (!st.empty() && a[i] > a[st.back()]) {2 ans[st.back()] = a[i];3 st.pop_back();4}5st.push_back(i);
第 2 章快刷
5 道题,覆盖循环队列、后缀表达式、括号匹配、两个栈做队列和出栈序列。先自己算出打印什么,再点选项。
MAX = 5 的循环队列(rear 指着下一个空位),front = 3,rear = 1,里面有几个?
1#include <iostream>2using namespace std;3 4const int MAX = 5;5 6int main() {7 int front = 3, rear = 1;8 cout << (rear - front + MAX) % MAX << "\n";9 return 0;10}
算后缀表达式 2 3 * 5 4 * + 9 −,打印几?
1#include <iostream>2#include <stack>3#include <string>4using namespace std;5 6int main() {7 string s = "23*54*+9-";8 stack<int> st;9 for (char c : s) {10 if (c >= '0' && c <= '9') {11 st.push(c - '0');12 } else {13 int b = st.top(); st.pop();14 int a = st.top(); st.pop();15 st.push(c == '+' ? a + b : c == '-' ? a - b : a * b);16 }17 }18 cout << st.top() << "\n";19 return 0;20}
检查 {[()()]} 时,栈里最多同时有几个括号?
1#include <iostream>2#include <string>3#include <algorithm>4using namespace std;5 6int main() {7 string s = "{[()()]}";8 int height = 0, best = 0;9 for (char c : s) {10 if (c == '(' || c == '[' || c == '{') height++;11 else height--;12 best = max(best, height);13 }14 cout << best << "\n";15 return 0;16}
两个栈做的队列:入 1 2,出,入 3 4,再出两次,打印什么?
1#include <iostream>2#include <stack>3using namespace std;4 5stack<int> in, out;6 7void enqueue(int x) { in.push(x); }8 9int dequeue() {10 if (out.empty())11 while (!in.empty()) {12 out.push(in.top());13 in.pop();14 }15 int x = out.top();16 out.pop();17 return x;18}19 20int main() {21 enqueue(1);22 enqueue(2);23 cout << dequeue() << " ";24 enqueue(3);25 enqueue(4);26 cout << dequeue() << " ";27 cout << dequeue() << "\n";28 return 0;29}
入栈顺序 1 2 3 4,一共有几种合法的出栈顺序?(next_permutation 把 24 种排列都试了一遍)
1#include <iostream>2#include <algorithm>3using namespace std;4 5bool valid(const int* out, int n) {6 int st[10], t = -1, k = 0;7 for (int x = 1; x <= n; x++) {8 st[++t] = x;9 while (t >= 0 && st[t] == out[k]) {10 t--;11 k++;12 }13 }14 return t == -1;15}16 17int main() {18 int p[] = {1, 2, 3, 4}, count = 0;19 do {20 if (valid(p, 4)) count++;21 } while (next_permutation(p, p + 4));22 cout << count << "\n";23 return 0;24}