package com.example.sgg.data.stack;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
/**
* 栈实现综合计算器(后缀表达式,即逆波兰表达式)
* Created by 奔跑的蜗牛 on 2021/7/22 0022.
* 每天学习一点点,每天进步一点点
* <p>
* 说明:
* 1.由于中缀表达式适用于人为计算,而逆波兰表达式更适用于计算机识别并计算
* 2.此计算器只为展示栈的应用,只写成整数运算,不适用于小数操作
* <p>
* 计算(3+4)x5-6 先转为逆波兰表达式 3 4 + 5 x 6 - 再进行运算
* 思路分析
* 从左到右扫描表达式,遇到数字时,直接入栈,遇到运算符时,弹出栈顶的两个元素,
* 用运算符对它们做相应的计算(次顶元素和栈顶元素),并将结果入栈;重复上述操作
* 直到表达式的最右端,最后运算得出的值即为表达式的结果
*/
public class PolandNotation {
public static void main(String[] args) {
//先定义一个逆波兰表达式
//(3+4)x5-6 => 3 4 + 5 x 6 - => 29
// 为了方便用空格隔开
String suffixExpression = "3 4 + 5 * 6 - ";
int res = PolandNotation.calculate(suffixExpression);
System.out.printf("表达式 %s=%d", suffixExpression, res);
}
/**
* 将表达式切割放进集合
*
* @param suffixExpression 表达式
* @return 集合
*/
public static List<String> getList(String suffixExpression) {
List<String> result = new ArrayList<>();
String[] split = suffixExpression.split(" ");
if (split.length != 0) {
result.addAll(Arrays.asList(split));
}
return result;
}
/**
* 完成逆波兰表达式的运算
* 将suffixExpression切割放入ArrayList中,将ArrayList配合栈完成计算
*/
public static int calculate(String suffixExpression) {
List<String> list = getList(suffixExpression);
//创建一个栈,一个即可
Stack<String> stack = new Stack<String>();
for (String item : list) {
if (item.matches("\\d+")) {
//匹配的是多位数
//入栈
stack.push(item);
} else {
//pop出两个数,并运算,再入栈
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("表达式的运算符有误:" + item);
}
stack.push(res + "");
}
}
return Integer.parseInt(stack.pop());
}
}