栈的应用——逆波兰表达式求值(力扣150)
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for(int i = 0; i < tokens.size(); i++){
if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/" ){
int num1 = st.top(); st.pop();
int num2 = st.top(); st.pop();
if(tokens[i] == "+") st.push(num2 + num1);//注意:先弹出的是右操作数!!
if(tokens[i] == "-") st.push(num2 - num1);
if(tokens[i] == "*") st.push(num2 * num1);
if(tokens[i] == "/") st.push(num2 / num1);
}
else{
st.push(tokens[i]);
}
}
return st.top();
}
};