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

4次阅读

共计 604 个字符,预计需要花费 2 分钟才能阅读完成。

中断表达式转后缀表达式

规定:
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 –

正文完
 0