力扣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 -

作者:月亮给蒙娜丽莎原文地址:https://segmentfault.com/a/1190000043780941

%s 个评论

要回复文章请先登录注册