关于c++:力扣150-逆波兰表达式求值

中断表达式转后缀表达式

规定:
1.数字本人排列
2.操作符:

a栈为空 || 优先级比栈顶高:入栈
b小于等于栈顶,就让栈顶pop,之后会有新的栈顶,接着比拟,直到满足条件a 

题解

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int>st;
        for(auto x:tokens)
        {
            if(x == "+")
            {
                int x =  st.top();
                st.pop();
                int y = st.top();
                st.pop();
                st.push(y+x);
            }
            else if(x == "-")
            {
                int x = st.top();
                st.pop();
                int y = st.top();
                st.pop();
                st.push(y-x);
            }
            else if(x == "*")
            {
                int x = st.top();
                st.pop();
                int y = st.top();
                st.pop();
                st.push(y*x);
            }
            else if(x == "/")
            {
                int x =st.top();
                st.pop();
                int y = st.top();
                st.pop();
                st.push(y/x);
            }
            else
            {
                st.push(stoi(x));
            }
        }
        return st.top();
    }

留神点

1.其余类型->string:to_string()

例题

例1:1+2*3/4+5-6转化为后缀表达式
解:1 2 3 * 4 / + 5 + 6 –

例2:1+(2+3)*4-5转化为后缀表达式
解:1 2 3 + 4 * + 5 –

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理