实现方法
- 从左至右扫描表达式
- 遇到数字时,将数字压栈,遇到运算符时,弹出栈顶的两个数,计算并将结果入栈
- 重复2直到表达式最右端,最后运算得出的值即为表达式的结果
示例:
计算后缀表达式的值:1 2 3 + 4 × + 5 -
- 从左至右扫描,将1,2,3压入栈;
- 遇到+运算符,3和2弹出,计算2+3的值,得到5,将5压入栈;
- 遇到4,将4压入栈
- 遇到×运算符,弹出4和5,计算5×4的值,得到20,将20压入栈;
- 遇到+运算符,弹出20和1,计算1+20的值,得到21,将21压入栈;
- 遇到5,将5压入栈;
- 遇到-运算符,弹出5和21,计算21-5的值,得到16为最终结果
代码实现
public class ReversePolishNotation {
public static void main(String[] args) {
String notation = "10 2 3 + 4 * + 5 -";
ReversePolishNotation reversePN = new ReversePolishNotation();
Stack<Integer> numStack = new Stack<>();
//以空格分隔上述表达式,存到数组中
String[] s = notation.split(" ");
//遍历数组
for (int i = 0; i < s.length; i++) {
if (!reversePN.isOperator(s[i])){
//如果不是运算符,则压栈
numStack.push(Integer.parseInt(s[i]));
} else {
//为运算符,则取出栈顶的两个数字进行运算
int result = reversePN.calculation(numStack.pop(), numStack.pop(), s[i]);
//将结果压栈
numStack.push(result);
}
}
//循环结束,栈中仅剩的一个元素及为结果
System.out.println(numStack.pop());
}
//判断是否是运算符
public boolean isOperator(String oper){
return oper.equals("+") ||oper.equals("-") ||oper.equals("*") ||oper.equals("/") ;
}
//计算
public int calculation(int num1, int num2, String oper){
switch (oper){
case "+":
return num2 + num1;
case "-":
return num2 - num1;
case "*":
return num2 * num1;
case "/":
return num2 / num1;
default:
return 0;
}
}
}