理论补充
后缀表达式(也叫逆波兰表达式)
规则:从左至右扫描表达式,遇到数字压入栈,遇到运算符,依次弹出栈顶两个数字进行运算,将运算结果压入栈,重复操作直到扫描到最右端。
eg:“3 4 + 5 x 6 -”
从左至右扫描将34压入栈,扫描到+弹出栈顶两个元素进行相加得7,再将7压入栈,扫描5压入栈,扫描到x弹出栈顶7 和 5进行运算得35,将35压入栈,继续扫描到6将其压入栈,扫描到-弹出栈顶两个元素运算35-6得到29得到最终结果
代码实现
package com.b0.a1_4stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static void main(String[] args) {
//1.定义逆波兰表达式 "3 4 + 5 x 6 -" = 29
//"30 4 + 5 x 6 -" = 164
//4 * 5 - 8 + 60 + 8 / 2 => 4 5 * 8 - 60 + 8 2 / + = 76
//说明,为了方便,数字和符号之间用空格隔开
String suffixExpression = "4 5 * 8 - 60 + 8 2 / + ";
//思路
//1.先将”3 4 + 5 x 6 -“放入ArrayList中
//2.将放入ArrayList传递给一个方法,遍历ArrayList配合栈完成计算
List<String> rpnList = getListString(suffixExpression);
System.out.println(calculate(rpnList));
}
//完成对逆波兰表达式的运算
public static int calculate(List<String> ls){
//创建一个栈
Stack<String> stack = new Stack<>();
for (String item : ls) {
if (item.matches("\\d+")){//正则表达式匹配为数字
stack.push(item);
}else{
int num1 = Integer.parseInt(stack.pop());
int num2 = Integer.parseInt(stack.pop());
int res = 0;
if (item.equals("+")){
res = num2 + num1;
} else if (item.equals("-")) {
res = num2 - num1;
}
else if (item.equals("*")) {
res = num2 * num1;
}
else if (item.equals("/")) {
res = num2 / num1;
}else {
throw new RuntimeException("运算符有错...");
}
stack.push(String.valueOf(res));
}
}
return Integer.parseInt(stack.pop());
}
//将逆波兰表达式,依次放入到ArrayList中,方便后续取值
public static List<String> getListString(String suffixExpression){
//将suffixExpression分割
String[] split = suffixExpression.split(" ");
List<String> list = new ArrayList<>();
for (String ele : split) {
list.add(ele);
}
return list;
}
}
本文介绍了一种计算逆波兰表达式(后缀表达式)的方法,通过使用栈来处理表达式中的数字和运算符,实现了逆波兰表达式的解析与计算过程。
3408

被折叠的 条评论
为什么被折叠?



