前缀表达式
后缀表达式(逆波兰)
public class PolandNotation {
public static void main(String[] args) {
String suffixExpression = "3 4 + 5 * 6 -";
List<String> list = getListString(suffixExpression);
int res = calculate(list);
System.out.println("计算的结果是:"+ res);
}
//将表达式转换成ArrayList
public static List<String> getListString(String suffixExpression){
String[] s = suffixExpression.split(" ");
List list = new ArrayList();
for (String l : s){
list.add(l);
}
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 num1 = Integer.parseInt(stack.pop());
int num2 = Integer.parseInt(stack.pop());
int res = 0;
if (item.equals("+")){
res = num1 + num2;
} 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(res + "");
}
}
return Integer.parseInt(stack.pop());
}
}