前缀表达式的计算机求值:eg:- × + 3 4 5 6
从右至左扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(栈顶元素和次顶元素),并将结果入栈;重复上述过程直到表达式最左端,最后运算得出的值即为表达式的结果。
中缀表达式:就是我们最常见的表达式:(3+4)×5-6
后缀表达式:又称逆波兰表达式与前缀表达式相似,只是运算符位于操作符之后。3 4 + 5 × 6 -。计算机求值:
从左至右扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,运算符对它们做相应的计算(次顶元素和栈顶元素),并将结果入栈;重复上述过程直到表达式最右端,最后运算得出的值即为表达式的结果。
public class PolandNotation {
public static void main(String[] args) {
//先定义逆波兰表达式
//(3+4)×5-6 ===》 3 4 + 5 × 6 -
String suffixExpression = "3 4 + 5 * 6 -";
//思路
//1.先将"3 4 + 5 × 6 -"放到ArrayList中
//2.将ArrayList传递给一个方法,配合栈 完成计算。
List<String> rpnList = getListString(suffixExpression);
System.out.println("rpnList" + rpnList);
int res = calculate(rpnList);
System.out.println("计算的结果是=" + res);
}
//将一个逆波兰表达式,依次将数据和运算符放入到ArrayList中
public static List<String> getListString(String suffixExpression) {
//将suffixExpression分割
String[] split = suffixExpression.split(" ");
List<String> list = new ArrayList<String>();
for (String ele : split) {
list.add(ele);
}
return list;
}
public static int calculate(List<String> ls) {
//创建一个栈
Stack<String> stack = new Stack<String>();
//遍历 ls
for (String item : ls) {
if (item.matches("\\d+")) {
stack.push(item);
}
else {
int num2 = Integer.parseInt(stack.pop());
int num1 = Integer.parseInt(stack.pop());
int res = 0;
if (item.equals("+")) {
res = num1 + num2;
} else if (item.equals("-")) {
res = num1 - num2;
} else if (item.equals("*")) {
res = num1 * num2;
} else if (item.equals("/")) {
res = num1 / num2;
} else {
throw new RuntimeException("运算符有误!!");
}
stack.push("" + res);
}
}
return Integer.parseInt(stack.pop());
}
}
运行结果: