中缀表达式转后缀表达式
规则:
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 -
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。