代码实现
package com.atguigu.stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static void main(String[] args) {
String suffixExpression = "4 5 * 8 - 60 + 8 2 / +";
List<String> rpnList = getListString(suffixExpression);
System.out.println("rpnList=" + rpnList);
int res = calculate(rpnList);
System.out.println("计算结果=" + res);
}
public static List<String> getListString(String 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>();
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());
}
}
运行结果
D:\java\jdk-11.0.11\bin\java.exe "-javaagent:D:\IntelliJ IDEA 2020.1.1\lib\idea_rt.jar=6923:D:\IntelliJ IDEA 2020.1.1\bin" -Dfile.encoding=UTF-8 -classpath E:\WHT\Project\Java\DataStructures\out\production\DataStructures com.atguigu.stack.PolandNotation
rpnList=[4, 5, *, 8, -, 60, +, 8, 2, /, +]
计算结果=76
Process finished with exit code 0