/**
* 将一个中缀表达式转换为后缀表达式
* @param s
*/
public static String InToend(String s) {
/**
* 1、运算数: 输出。
* 2、左括号::入栈。
* 3、右括号:将栈顶的运算符弹出并输出,直到遇到左括号(弹出但不输出)。
* 4、运算符:
* 1、如果优先级大于栈顶运算符,则入栈;
* 2、如果优先级小于栈顶运算符,则弹出栈顶运算符,并输出,
* 接着继续比较新的栈顶运算符,
* 直到该运算符优先级大于栈顶运算符,然后入栈。
* 5、如果表达式处理完毕,将堆栈中的运算符弹出,并输出。
*/
StringBuilder sb = new StringBuilder();
Stack<Character> st = new Stack<>();
Map<Character,Integer> map = new HashMap<Character,Integer>();
//存储运算符的优先级(逻辑)
map.put('+', 1);
map.put('-', 1);
map.put('*', 3);
map.put('/', 3);
char[] cs = s.toCharArray();
for(int i = 0 ; i < cs.length; i++) {
char c = cs[i];
//[48-57]
if(c-0 <= 57 && c-0 >= 48) { //运算数
sb.append(c);
}else if(c == '(') { //左括号
st.push(c);
}else if(c == ')') { //右括号
char c1;
while((c1 = st.pop())!= '(') {
sb.append(c1);
}
}else { //运算符
if(st.isEmpty()) { //栈空,直接入栈
st.push(c); continue;
}
char cTop = st.peek(); //栈顶元素
Integer topPriority = map.get(cTop); //栈顶运算符的优先级
Integer currPriority = map.get(c); //当前运算符的优先级
if(cTop == '(') { //左括号,优先级最低,运算符入栈
st.push(c);
}else if(currPriority > topPriority) { //当前运算符优先级 > 栈顶
st.push(c);
}else if(currPriority <= topPriority) {
//循环,将栈顶运算符优先级大于当前运算符的运算符弹出,并输出。
while(!st.isEmpty() && st.peek() != '(' && currPriority <= topPriority) {
sb.append(st.pop());
if(!st.isEmpty())
topPriority = map.get(st.peek()); //栈顶新运算符的优先级
}
st.push(c);
}
}
}
//将栈中运算符弹出
while(!st.isEmpty()) {
sb.append(st.pop());
}
System.out.println(sb);
return sb.toString();
}
//计算后缀表达式的值
public static void calc(String s) {
/**
* 1、将运算数入栈。
* 2、如果遇到运算符,弹出栈中的两个运算数,进行计算后入栈。
* 3、重复以上操作,直到结束,栈中的元素就是结果。
*/
Stack<String> st = new Stack<String>();
char[] cs = s.toCharArray();
for(int i = 0; i < cs.length; i++) {
char c = cs[i];
switch(c) {
case '+':
Double num1 = Double.parseDouble(st.pop()) + Double.parseDouble(st.pop());
st.push(num1+"");
break;
case '-':
String pop1 = st.pop();
String pop2 = st.pop();
Double num2 = Double.parseDouble(pop2) - Double.parseDouble(pop1);
st.push(num2+"");
break;
case '*':
Double num3 = Double.parseDouble(st.pop()) * Double.parseDouble(st.pop());
st.push(num3+"");
break;
case '/':
String pop3 = st.pop();
String pop4 = st.pop();
Double num4 = Double.parseDouble(pop4) / Double.parseDouble(pop3);
st.push(num4+"");
break;
default: st.push(c+"");break;
}
}
System.out.println(st.pop());
}
测试:
public static void main(String[] args) {
String s = "1+2*(3+4)+5/6";
String s1 = "1+2*3+4+5/6";
String s2 = "1+2+(3+4)+5-6";
String s3 = "1*2*(3/4)*5/6";
String s4 = "1*2+(3+4*(5+6)/7+8)+9";
String s5 = "(1*2+(3+4*(5+6)/7+8)+9)";
String s6 = "1+(2-3)*4+4/2";
//将中缀表达式转为后缀表达式
String ss = InToend(s);
String ss1 = InToend(s1);
String ss2 = InToend(s2);
String ss3 = InToend(s3);
String ss4 = InToend(s4);
String ss5 = InToend(s5);
String ss6 = InToend(s6);
System.out.println("--------------------------");
//计算后缀表达式的值
calc(ss); //15.83
calc(ss1); //11.83
calc(ss2); //9.0
calc(ss3); //1.25
calc(ss4); //28.28
calc(ss5); //28.28
calc(ss6); //-1
}
结果: