逆波兰计算器
1. 思路分析:
(3+4)×5-6
对应的后缀表达式就是 3 4 + 5 × 6 -
, 针对后缀表达式求值步骤如下:
- 从左至右扫描,将 3 和 4 压入堆栈;
- 遇到+运算符,因此弹出 4 和 3(4 为栈顶元素,3 为次顶元素),计算出 3+4 的值,得 7,再将 7 入栈;
- 将 5 入栈;
- 接下来是×运算符,因此弹出 5 和 7,计算出 7×5=35,将 35 入栈;
- 将 6 入栈;
- 最后是-运算符,计算出 35-6 的值,即 29,由此得出最终结果。
2. 代码实现:
/**
* 逆波兰表达式(后缀表达式)求值
*/
public class PolandNotation {
/**
* 测试
* @param args
*/
public static void main(String[] args) {
String expression = "3 4 + 5 * 6 -";
List<String> list = stringToList(expression);
int result = calculate(list);
System.out.println("计算结果为:" + result);
}
/**
* 具体计算后缀表达式
* @param list 表示后缀表达式的ArrayList
* @return 返回计算结果
*/
public static int calculate(List<String> list) {
int result = 0;
Stack<String> stack = new Stack<>();
for (String element : list) {
if (element.matches("\\d+")) {
stack.push(element);
} else if ("+".equals(element)) {
int num1 = Integer.parseInt(stack.pop());
int num2 = Integer.parseInt(stack.pop());
result = num2 + num1;
stack.push("" + result);
} else if ("-".equals(element)) {
int num1 = Integer.parseInt(stack.pop());
int num2 = Integer.parseInt(stack.pop());
result = num2 - num1;
stack.push("" + result);
} else if ("*".equals(element)) {
int num1 = Integer.parseInt(stack.pop());
int num2 = Integer.parseInt(stack.pop());
result = num2 * num1;
stack.push("" + result);
} else if ("/".equals(element)) {
int num1 = Integer.parseInt(stack.pop());
int num2 = Integer.parseInt(stack.pop());
result = num2 / num1;
stack.push("" + result);
} else {
throw new RuntimeException("表达式有误!");
}
}
return Integer.parseInt(stack.pop());
}
/**
* 将字符串类型的表达式转换为ArrayList
* @param expression 后缀表达式
* @return 返回表示后缀表达式的ArrayList
*/
public static List<String> stringToList(String expression) {
List<String> list = new ArrayList<>();
String[] split = expression.split(" ");
for (String s : split) {
list.add(s);
}
return list;
}
}