中序表达式转为后续表达式,并实现后续表达式的计算
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class InfixToSuffix {
public static void main(String[] args) {
InfixToSuffix o = new InfixToSuffix();
String s = "(3+4)*5-6"; // 3 4 + 5 * 6 -
String s1 = "(3+4)*5"; // 3 4 + 5 * 6 -
// List<String> res = o.infixToSuffix(s);
int calculator = o.calculator(s1);
System.out.println(calculator);
}
public int calculator(String data){
List<String> suffix = infixToSuffix(data);//中序表达式转为后续表达式
Stack<Integer> temp=new Stack<Integer>();//结果栈
//后续表达式计算: 遇到数字就入栈,遇到符号,,则出栈两次进行计算,结果入栈,最后栈中则为计算的结果
int num1,num2;
for(String s:suffix){
switch (s) {
case "+":
num2=temp.pop();
num1=temp.pop();
temp.push(num1+num2);
break;
case "-":
num2=temp.pop();
num1=temp.pop();
temp.push(num1-num2);
break;
case "*":
num2=temp.pop();
num1=temp.pop();
temp.push(num1*num2);
break;
case "/":
num2=temp.pop();
num1=temp.pop();
temp.push(num1/num2);
break;
default:
//数字入栈
temp.push(Integer.parseInt(s));
break;
}
}
return temp.pop();
}
// 中序表达式转为后续表达式
private List<String> infixToSuffix(String data) {
List<String> da = new ArrayList<String>();// data数据集合
List<String> res = new ArrayList<String>();// 结果集合
Stack<String> oper = new Stack<String>();// 临时操作栈
for (int i = 0; i < data.length(); i++) {
da.add(data.charAt(i) + "");
}
// System.out.println(da);
for (String s : da) {
// 如果是数,直接入res
if (s.matches("\\d+")) {
res.add(s);
} else {
// 如果是符号
// 1. oper栈为空 或者 符号位( ,或者栈不空且栈顶符号位( 直接入符号栈
if (oper.isEmpty() || s.equals("(")||oper.peek().equals("(")) {
oper.push(s);
} else if (s.equals(")")) {
// 2. 当前符号为 ) ,oper栈出栈,加入到res,直到遇到(,oper出栈
while (!oper.peek().equals("(")) {
res.add(oper.pop());
}
oper.pop();// 去掉oper中的 (
} else if (priority(s) > priority(oper.peek())) {
// 3. 否则 如果 oper栈不空,当前符号优先级高于oper栈顶,则当前符号入res
res.add(s);
} else {
// 4. 否则 当前符号优先级小于等于oper栈顶 ,则oper出栈加入res,直到当前优先级大于oper栈顶优先级,当前符号入oper栈。
while (!oper.isEmpty() &&priority(s) <= priority(oper.peek())) {
res.add(oper.pop());
}
oper.push(s);
}
}
}
// 5. 将oper栈出栈,到res,直到oper为空
while (!oper.isEmpty()) {
res.add(oper.pop());
}
return res;
}
// 优先级的判定
private int priority(String oper) {
int p1 = 1;
int p2 = 2;
int res;
switch (oper) {
case "+":
res = p1;
break;
case "-":
res = p1;
break;
case "*":
res = p2;
break;
case "/":
res = p2;
break;
default:
res = -1;
break;
}
return res;
}
}