栈——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();

    }
};

相关推荐
智算菩萨9 小时前
【Python机器学习】支持向量机(SVM)完全指南:从理论到实践的深度探索
算法·机器学习·支持向量机
中國龍在廣州9 小时前
2025,具身智能正在惩罚“持有者”
人工智能·深度学习·算法·自然语言处理·chatgpt
爱学习的capoo9 小时前
电气控制与PLC考点(自用)
算法
byzh_rc9 小时前
[算法设计与分析-从入门到入土] 递归
数据库·人工智能·算法·机器学习·支持向量机
Yuer20259 小时前
WebRTC 实时语音交互如何支持“可中断”?为什么状态机(FSM)是绕不开的方案
算法·rust·webrtc·fsm
CoderCodingNo9 小时前
【GESP】C++五级真题(数论、埃氏筛思想考点) luogu-B3969 [GESP202403 五级] B-smooth 数
开发语言·c++·算法
思成Codes9 小时前
数据结构: 权值线段树——线段树系列(提供模板)
数据结构·算法
历程里程碑9 小时前
破解三数之和:双指针高效解法
c语言·数据结构·c++·经验分享·算法·leetcode·排序算法
Vect__9 小时前
25.12.27 算法日记——双指针
c++·算法
Swizard9 小时前
数据不够代码凑?用 Albumentations 让你的 AI 模型“看”得更广,训练快 10 倍!
python·算法·ai·训练