Java inverse Polish expression result (stack)
What is inverse Polish expression?
逆波兰表达式求值问题是我们计算机中经常遇到的一类问题,要研究明白这个问题,首先我们得搞清楚什么是逆波
兰表达式?要搞清楚逆波兰表达式,我们得从中缀表达式说起。
中缀表达式:
中缀表达式就是我们平常生活中使用的表达式,例如:1+3*2,2-(1+3)等等,中
缀表达式的特点是:二元运算符总是置于两个操作数中间。中缀表达式是人们最喜欢的
表达式方式,因为简单,易懂。但是对于计算机来说就不是这样了,因为中缀表达式的
运算顺序不具有规律性。不同的运算符具有不同的优先级,如果计算机执行中缀表达式,
需要解析表达式语义,做大量的优先级相关操作。
逆波兰表达式(后缀表达式):
逆波兰表达式是波兰逻辑学家J・卢卡西维兹(J・ Lukasewicz)于1929年首先
提出的一种表达式的表示方法,后缀表达式的特点:运算符总是放在跟它相关的操作
数之后。
Illustration:
Requirements:
中缀表达式 3*(17-15)+18/6 的逆波兰表达式如下:
String[] notation = {
"3", "17", "15", "-", "*","18", "6","/","+"};
求出该逆波兰表达式的结果
analysis:
1.创建一个栈对象oprands存储操作数
2.从左往右遍历逆波兰表达式,得到每一个字符串
3.判断该字符串是不是运算符,如果不是,把该该操作数压入oprands栈中
4.如果是运算符,则从oprands栈中弹出两个操作数o1,o2
5.使用该运算符计算o1和o2,得到结果result
6.把该结果压入oprands栈中
7.遍历结束后,拿出栈中最终的结果返回
Illustration:
Code:
public class ReversePolishNotationTest {
public static void main(String[] args) {
//中缀表达式 3*(17-15)+18/6 的逆波兰表达式如下 6+3=9
String[] notation = {
"3", "17", "15", "-", "*", "18", "6", "/", "+"};
int result = caculate(notation);
System.out.println("逆波兰表达式的结果为:" + result);
}
private static int caculate(String[] notation) {
//1.定义一个栈,用来存储操作数
Stack<Integer> oprands = new Stack<>();
//2.从左往右遍历逆波兰表达式,得到每一个元素
for(int i =0; i <notation.length; i++){
String curr = notation[i];
//3.判断当前元素是否是运算符还是操作数
Integer o1;
Integer o2;
Integer result;
switch (curr){
//4.运算符,从栈中弹出两个操作数,完成运算,运算完的结果再压入栈中
case "+":
o1 = oprands.pop();
o2 = oprands.pop();
result = o2 + o1;
oprands.push(result);
break;
case "-":
o1 = oprands.pop();
o2 = oprands.pop();
result = o2 - o1;
oprands.push(result);
break;
case "*":
o1 = oprands.pop();
o2 = oprands.pop();
result = o2 * o1;
oprands.push(result);
break;
case "/":
o1 = oprands.pop();
o2 = oprands.pop();
result = o2 / o1;
oprands.push(result);
break;
default:
//5.操作数,把该操作数压栈
oprands.push(Integer.parseInt(curr));
break;
}
}
//6.得到栈中最后一个元素,就是逆波兰表达式的结果
int result = oprands.pop();
return result;
}
}
operation result: