栈——OJ题

📘北尘_个人主页
🌎个人专栏 :《Linux操作系统》《经典算法试题 》《C++》 《数据结构与算法》

☀️走在路上,不忘来时的初心

文章目录


一、最小栈

1、题目讲解

2、思路讲解

3、代码实现

cpp 复制代码
class MinStack {
public:
    MinStack() {}
    
    void push(int val) {
        st.push(val);
        if(minst.empty() || st.top()<=minst.top())
        {
            minst.push(val);
        }
    }
    
    void pop() {
        if(st.top()==minst.top())  
        {
             minst.pop();
        }
       
        st.pop();


    }
    
    int top() {
        return st.top();
    }
    
    int getMin() {
        return minst.top();

    }
    stack<int> st;
    stack<int> minst;
};

二、栈的压入、弹出序列

1、题目讲解

2、思路讲解

3、代码实现

cpp 复制代码
bool IsPopOrder(vector<int>& pushV, vector<int>& popV) 
    {
        stack<int> s;
        int pushi=0,popi=0;
        for(auto ch:pushV)
        {
            s.push(pushV[pushi]);
            pushi++;
            while(!s.empty() && s.top()==popV[popi])
            {
                s.pop();
                popi++;
            }
        }
        return s.empty();
    }

三、逆波兰表达式求值

1、题目讲解

2、思路讲解

3、代码实现

cpp 复制代码
class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> s;
        for(auto& ch:tokens)
        {
            if(ch=="+" || ch=="-" || ch=="*" || ch=="/" )
            {
                int right=s.top();
                s.pop();
                int left=s.top();
                s.pop();
                switch(ch[0])
                {
                    case '+':
                    s.push(left+right);
                    break;

                    case '-':
                    s.push(left-right);
                    break;

                    case '*':
                   s.push(left*right);
                    break;

                    case '/':
                   s.push(left/right);
                    break;  
                }
            }
            else
            {
                s.push(stoi(ch));
            }
        }

        return s.top();

    }
};

相关推荐
圣光SG8 小时前
Java操作题练习(七)
java·开发语言·算法
Cx330_FCQ9 小时前
Tmux使用
服务器·git·算法
拳里剑气10 小时前
C++算法:多源BFS
c++·算法·宽度优先·多源bfs
ysa05103011 小时前
【板子】短序列dp(换成维护更小常数维度的dp)
c++·笔记·算法·板子
shwill12311 小时前
PID 算法(三)--- 增量 PID ↔ 单神经元 PID 等价映射
linux·算法
wabs66612 小时前
关于图论【卡码网110.字符串迁移的思考】
数据结构·算法·图论
hanlin0312 小时前
刷题笔记:力扣第242、349题(哈希表)
笔记·算法·leetcode
浮沉98713 小时前
二分查找算法例题(二)
算法
only-qi14 小时前
大模型Agent面试攻略:落地工程痛点、评估体系与Agentic RAG核心精讲
人工智能·算法·面试·职场和发展·langchain·rag
Gauss松鼠会16 小时前
【GaussDB】GaussDB锁阻塞源头查询
java·开发语言·前端·数据库·算法·gaussdb·经验总结