在这里插入图片描述
/**
* 逆波兰表达式
*/
public class NiBoLanCalculatorDemo {
public static void main(String[] args) {
String str = "1+((2+3)*4)-5";
List<String> list = toArray(str);
List<String> bolanList = listToBoLan(list);
System.out.println(bolanList);
int calculation = calculation(bolanList);
System.out.println(calculation);
}
/**
* 将中缀表达式转换为波兰表达式
*
* @param ls
* @return
*/
public static List<String> listToBoLan(List<String> ls) {
Stack<String> s1 = new Stack<>();
List<String> s2 = new ArrayList<>();
for (String item : ls) {
if (item.matches("\\d+")) {
s2.add(item);
}else{
if (item.equals("(")) {
s1.push(item);
}else if(item.equals(")")){
while (!s1.peek().equals("(")){
s2.add(s1.pop());
}
s1.pop();
}else{
while (s1.size()!= 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item)){
s2.add(s1.pop());
}
s1.add(item);
}
}
}
while (s1.size() != 0) {
s2.add(s1.pop());
}
return s2;
}
/**
* 将 中缀表达式转换为list
*
* @param str
* @return
*/
public static List<String> toArray(String str) {
str = str.replaceAll(" ", "");
List<String> res = new ArrayList<>();
int index = 0;
char ch;
String sub = "";
while (index < str.length()) {
ch = str.charAt(index);
if (!String.valueOf(ch).matches("\\d")) {
res.add(String.valueOf(ch));
} else {
sub = String.valueOf(ch);
// 如果当前索引的下一个节点 是数字
while (index < str.length()-1 &&
str.charAt(index + 1) > 47
&& str.charAt(index + 1) < 58) {
sub += String.valueOf(str.charAt(index + 1));
index++;
}
res.add(sub);
sub = "";
}
index++;
}
return res;
}
/**
* 逆波兰表达式计算方法
*
* @param ls
* @return
*/
public static int calculation(List<String> ls) {
Stack<String> stack = new Stack<>();
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(String.valueOf(res));
}
}
return Integer.parseInt(stack.pop());
}
}
class Operation{
public static int ADD = 1;
public static int SUB = 1;
public static int MUL = 2;
public static int DIV = 2;
public static int getValue(String op) {
switch (op) {
case "+":
return ADD;
case "-":
return SUB;
case "*":
return MUL;
case "/":
return DIV;
default:
return -1;
}
}
}在这里插入图片描述