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

    }
};

相关推荐
是小Y啦几秒前
leetcode 106.从中序与后续遍历序列构造二叉树
数据结构·算法·leetcode
liuyang-neu11 分钟前
力扣 42.接雨水
java·算法·leetcode
y_dd18 分钟前
【machine learning-12-多元线性回归】
算法·机器学习·线性回归
m0_6312704018 分钟前
标准c语言(一)
c语言·开发语言·算法
万河归海42819 分钟前
C语言——二分法搜索数组中特定元素并返回下标
c语言·开发语言·数据结构·经验分享·笔记·算法·visualstudio
小周的C语言学习笔记23 分钟前
鹏哥C语言36-37---循环/分支语句练习(折半查找算法)
c语言·算法·visual studio
y_dd23 分钟前
【machine learning-七-线性回归之成本函数】
算法·回归·线性回归
小魏冬琅39 分钟前
K-means 算法的介绍与应用
算法·机器学习·kmeans
凌肖战1 小时前
力扣上刷题之C语言实现(数组)
c语言·算法·leetcode
秋夫人2 小时前
B+树(B+TREE)索引
数据结构·算法