文章目录
一、算法介绍
栈:后入先出
栈系列问题:https://leetcode-cn.com/tag/stack/problemset/
栈的典型问题
-
设计题
-
括号、表达式运算、字符串退格
-
单调栈
-
树的遍历 - 深度优先
-
图的遍历 - 深度优先
二、解题模板
1、栈的实现
// 用数组实现栈
#include <iostream>
class MyStack {
private:
vector<int> data; // store elements
public:
/** Insert an element into the stack. */
void push(int x) {
data.push_back(x);
}
/** Checks whether the queue is empty or not. */
bool isEmpty() {
return data.empty();
}
/** Get the top item from the queue. */
int top() {
return data.back();
}
/** Delete an element from the queue. Return true if the operation is successful. */
bool pop() {
if (isEmpty()) {
return false;
}
data.pop_back();
return true;
}
};
2、栈的API
#include <iostream>
#include <stack>
int main() {
// 1. 初始化栈
stack<int> s;
// 2. 入栈.
s.push(5);
s.push(13);
// 3. 判断栈空
if (s.empty()) {
cout << "Stack is empty!" << endl;
return 0;
}
// 4. 出栈.
s.pop();
// 5. 获取栈顶元素.
s.top() ;
// 6. 获取栈大小.
s.size() ;
}
3、深度优先
方法1:递归实现
boolean DFS(Node cur, Node target, Set<Node> visited) {
return true if cur is target; //如果找到则返回
for (next : each neighbor of cur) { //遍历当前节点的所有邻居节点
if (next is not in visited) { //如果next没有被遍历则加入遍历列表
add next to visted;
return true if DFS(next, target, visited) == true; //递归进行深度优先遍历
}
}
return false;
}
方法2:显式栈
boolean DFS(int root, int target) {
Set<Node> visited;
Stack<Node> s;
add root to s; //添加根节点
while (s is not empty) { //当栈不为空
Node cur = the top element in s; //取栈顶元素
return true if cur is target; //如果找到则返回
for (Node next : the neighbors of cur) { //遍历邻居节点
if (next is not in visited) { //若未被访问,则入栈并标记遍历
add next to s;
add next to visited;
}
}
remove cur from s; //删除当前元素
}
return false;
}