中断表达式转后缀表达式
规定:
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 -