注意:中缀表达式需要空格隔开操作数或者操作符
关键有:判断是否操作符,操作符优先级
public class ProfixExpression {
public static void main(String[] args) {
String midToProfixStr=midToPro("3 + ( 2 + 5 ) * 4 + 6");
System.out.println(midToProfixStr);
System.out.println(profixCalculate(midToProfixStr));
}
/**
* 计算排好的后缀操作计算式
* @param proStr
* @return
*/
public static int profixCalculate(String proStr){
MyStack<Integer> st=new MyStack<>();
String[] arr=proStr.trim().split(" ");
for(int i=0;i<arr.length;i++){
if(!isOperator(arr[i])){
st.push(Integer.valueOf(arr[i]));
}else{
int x=st.pop();
int y=st.pop();
st.push(operate(y,x,arr[i]));
}
}
return st.pop();
}
/**
* 对合适的操作进行算术运算
* @param x 后出栈操作数
* @param y 先出栈操作数
* @param operator
* @return
*/
private static Integer operate(int x, int y, String operator) {
switch(operator){
case "+":
return x+y;
case "-":
return x-y;
case "*":
return x*y;
case "/":
return x/y;
default:
return 0;
}
}
/**
* 判断字符串是否是操作符
* @param op 操作符
* @return
*/
private static boolean isOperator(String op) {
if(op.equals("+")||op.equals("-")||op.equals("*")||op.equals("/")||op.equals("(")||op.equals(")")){
return true;
}
return false;
}
/**
* 把中缀表达式转化为后缀表达式
* @param mid
* @return
*/
public static String midToPro(String mid){
String outStr="";
MyStack<String> st=new MyStack<>();
String[] arr=mid.trim().split(" ");
System.out.println(arr[2]);
for(int i=0;i<arr.length;i++){
if(!isOperator(arr[i])){
//不是操作符
outStr=outStr+arr[i]+" ";
}else{
//是操作符
if(st.isEmpty()){
//空栈,直接入栈
st.push(arr[i]);
System.out.println("第一个"+st.getSize());
}else{
//非空栈
if(arr[i].equals(")")){
//遇到右括号怎么办
System.out.println("遇上右括号"+st.getSize());
while(!(st.peek().equals("("))){
outStr=outStr+st.pop()+" ";
System.out.println("遇上右括号"+st.getSize());
}
st.pop();
}else{
//当栈非空,也不是右括号的操作符号时
System.out.println("遇上操作符前"+st.getSize());
int curPrio=getPrio(arr[i]);//**拿到读到的操作符的优先级**
System.out.println("=="+curPrio);
while((!st.isEmpty())&&(!st.peek().equals("("))&&(getPrio(st.peek())>=curPrio)){
outStr=outStr+st.pop()+" ";
}
st.push(arr[i]);
System.out.println("遇上操作符后"+st.getSize());
}
}
}
}
while(!st.isEmpty()){
outStr=outStr+st.pop()+" ";
}
return outStr;
}
public static int getPrio(String op){
switch(op){
case "+":
return 1;
case "-":
return 1;
case "*":
return 2;
case "/":
return 2;
case "(":
return 5;
}
return 0;
}
}