中缀转后缀步骤:
- 初始化运算符栈s1和存储结果的结合result
- 从左至右扫描中缀表达式
- 遇到操作数时,将其存储到result
- 遇到运算符时,比较其与s1栈顶运算符的优先级
- 如果s1为空,或栈顶运算符为左括号“(”,则直接将此运算符入栈
- 否则,若优先级比栈顶运算符的高,也将运算符压入s1
- 否则,将循环将s1栈顶的运算符弹出并加入到集合中,直到栈为空或扫描到数字或元素的优先级大于栈顶的优先级为止
package polan;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolanNotation {
public static void main(String[] args){
ArrayList<String> strings = new ArrayList<>();
String string = "7 + 8 * ( 10 - 1 )";
String[] s = string.split(" ");
for (String temp : s) {
strings.add(temp);
}
System.out.println("calculator = " + calculator(changeExpression(strings)));
}
//中缀变后缀
public static List<String> changeExpression(List<String> infix){
Stack<String> s1 = new Stack<>();
ArrayList<String> result = new ArrayList<>();
for (String el : infix) {
//如果为数字,直接存入result中
if (el.matches("\\d+")){
result.add(el);
}else{
//如果是运算符,进行判断
//如果栈为空,或者元素为“(”,或者优先级大于栈顶的优先级,则直接压栈
if (s1.isEmpty() || el.equals("(") ||getValue(el) > getValue(s1.peek()) ){
s1.push(el);
//如果为“)”,则循环栈,直到找到“)”,进行消除
}else if (el.equals(")")){
while (true){
String pop = s1.pop();
if (pop.equals("(")){
break;
}
result.add(pop);
}
}
else {
while (s1.size() != 0 && getValue(el) <= getValue(s1.peek())){
result.add(s1.pop());
}
s1.push(el);
}
}
}
//将s1中剩余的元素弹出添加到result中
while (s1.size() != 0){
result.add(s1.pop());
}
return result;
}
public static int getValue(String pro){
switch(pro){
case "+":
return 1;
case "-":
return 1;
case "*":
return 2;
case "/":
return 2;
default:
return -1;
}
}
public static int calculator(List<String> expression){
Stack<String> numbers = new Stack<>();
int num1 = 0;
int num2 = 0;
for (String el : expression) {
boolean res = el.matches("\\d+");
if (res){
numbers.push(el);
}else {
num1 = Integer.parseInt(numbers.pop());
num2 = Integer.parseInt(numbers.pop());
switch(el){
case "+":
numbers.push(String.valueOf(num1 + num2));
break;
case "-":
numbers.push(String.valueOf(num2 - num1));
break;
case "*":
numbers.push(String.valueOf(num1 * num2));
break;
case "/":
numbers.push(String.valueOf(num2 / num1));
break;
default:
System.out.println("what are you 弄啥嘞");
}
}
}
return Integer.parseInt(numbers.pop());
}
}