【刷题总结】栈系列问题

本文详细介绍了栈在算法中的应用,包括栈的基础特征、解题模板和具体问题解决。通过栈的实现、API、深度优先策略,探讨了括号匹配、表达式运算、退格问题、单调栈、树的深度优先遍历和图的深度优先遍历等经典问题。文章深入浅出,提供了丰富的解题思路和模板,是理解栈在算法中作用的宝贵资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、算法介绍

栈:后入先出

栈系列问题: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;
}

4、单调栈问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值