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

    }
};

相关推荐
心中有国也有家8 小时前
cann-recipes-infer:昇腾 NPU 推理的“菜谱集合”
经验分享·笔记·学习·算法
绝知此事9 小时前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
碧海银沙音频科技研究院9 小时前
通话AEC与语音识别AEC的软硬回采链路
深度学习·算法·语音识别
csdn_aspnet9 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
m0_6294947312 小时前
LeetCode 热题 100-----26.环形链表 II
数据结构·算法·leetcode·链表
壹号用户12 小时前
用队列实现栈
数据结构·算法
做人求其滴13 小时前
面试经典 150 题 380 274
c++·算法·面试·职场和发展·力扣
daad77713 小时前
记一组无人机IMU传感器数据
算法
计算机安禾13 小时前
【c++面向对象编程】第42篇:模板特化与偏特化:为特定类型定制实现
开发语言·c++·算法