1. 逆波兰表达式求值解析与实现
1.1 逆波兰表达式原理
逆波兰表达式(Reverse Polish Notation,RPN)是一种数学表达式的书写方式,其特点是运算符位于操作数之后。这种表示法最大的优势是不需要括号来标识运算的优先级,所有运算顺序完全由操作符的位置决定。
传统中缀表达式:(2 + 3) * 4
逆波兰表达式:2 3 + 4 *
这种表达式的计算过程天然适合用栈结构来实现。当遇到数字时压入栈中,遇到运算符时弹出栈顶的两个元素进行计算,然后将结果重新压入栈中。整个过程只需要一次从左到右的扫描即可完成计算。
1.2 代码实现详解
cpp复制class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for (auto& x : tokens){
char c = x[0];
// 处理数字(包括负数)
if (x.size() > 1 || isdigit(c)) {
st.push(stoi(x));
continue;
}
// 弹出第二个操作数
int s = st.top();
st.pop();
// 根据运算符进行计算
if(c == '+'){
st.top() += s;
}else if (c == '-'){
st.top() -= s;
}else if (c == '*'){
st.top() *= s;
}else{
st.top() /= s;
}
}
return
