基础栈操作-求解波兰表达式
题目:根据逆波兰表示法,求表达式的值。
有效的运算符包括
。每个运算对象可以是整数,也可以是另一个逆波兰表达式
说明
整数除法只保留整数部分。给定逆波兰表达式总是有效的。换句话说,表达式总会得岀有效数值且不存在 除数为0的情况。
示例1
输入:[“2”,“1”,"+",“3”,"* 输出:9
解释:该算式转化为常见的中缀算术表达式为:(2+1)*3)=9
分析:注意cpp中各类型,单引号和双引号不一样。注意栈的取值操作int x = st.top(); st.pop();
#include "_myPrint.cpp"
#include "stack"
#include "string"
using namespace std;
class Solution{
public:
int bolan(vector<string>& arrIn){
stack<int> st;
for (int i = 0; i < arrIn.size(); i++){
if (arrIn[i] == "+" || arrIn[i] == "-" || arrIn[i] == "*" || arrIn[i] == "/"){
int num1 = st.top();
st.pop();
int num2 = st.top();
st.pop();
int num;
if (arrIn[i] == "+") num = num2 + num1;
else if (arrIn[i] == "-") num = num2 - num1;
else if (arrIn[i] == "*") num = num2 * num1;
else if (arrIn[i] == "/") num = num2 / num1;
st.push(num);
}
else {
st.push(stoi(arrIn[i]));
}
}
int res = st.top();
st.pop();
return res;
}
};
int main(){
Solution s;
vector<string> arr = {"4", "13", "5", "/", "+"};
int res = s.bolan(arr);
cout << res << endl;
}