public class test {
public static void reversePolishNotation(String s) {
//运算符优先关系从大到小
// *(/) +(-) #
Map<Character, Integer> hm = new HashMap<>();
hm.put('#', 0);
hm.put('+', 1);
hm.put('-', 1);
hm.put('*', 2);
hm.put('/', 2);
//去除前导、后导空格,尾部添加 #
s = s.trim() + "#";
long num = 0L;
String operator = "+-*/";
//运算符栈
List<Character> operatorStack = new ArrayList<>();
//从左向右遍历表达式
for(char c : s.toCharArray()) {
//跳过空格
if(' ' == c)
continue;
//遍历到数字则获取完整数字
if(Character.isDigit(c)) {
num = num * 10 + (c - 48);
continue;
}
//输出数字
System.out.print(num + " ");
num = 0;
//遍历到 +-*/
if(operator.contains(c + ""))
while(true)
//栈空,运算符入栈
if(operatorStack.isEmpty()) {
operatorStack.add(c);
break;
//栈非空,当前运算符优先级大于栈顶运算符,运算符入栈
} else if(hm.get(c) > hm.get(operatorStack.get(operatorStack.size() - 1))) {
operatorStack.add(c);
break;
//栈非空,当前运算符优先级不大于栈顶运算符,栈顶运算符出栈输出
} else {
System.out.print(operatorStack.get(operatorStack.size() - 1) + " ");
operatorStack.remove(operatorStack.size() - 1);
}
//遍历到 ()#
else
//遍历到左括号,左括号入栈
if('(' == c) {
operatorStack.add(c);
//遍历到右括号
} else if(')' == c) {
boolean isExit = false;
while(true)
//栈顶为左括号,左括号出栈
if('(' == operatorStack.get(operatorStack.size() - 1)) {
operatorStack.remove(operatorStack.size() - 1);
//栈顶不为左括号,栈空,表达式错误
} else if(operatorStack.isEmpty()) {
isExit = true;
break;
//栈顶不为左括号,栈非空,栈顶运算符出栈
} else {
System.out.print(operatorStack.get(operatorStack.size() - 1) + " ");
operatorStack.remove(operatorStack.size() - 1);
}
if(isExit)
break;
//遍历到 #
} else {
boolean isExit = false;
while(true)
//栈空,求逆波兰表达式完成
if(operatorStack.isEmpty()) {
//System.out.println("\nReverse Polish Notation Done");
isExit = true;
break;
//栈非空,栈顶为左括号,表达式错误
} else if('(' == operatorStack.get(operatorStack.size() - 1)) {
System.out.println("ERROR");
isExit = true;
break;
//栈非空,栈顶不为左括号,栈顶运算符出栈
} else {
System.out.print(operatorStack.get(operatorStack.size() - 1) + " ");
operatorStack.remove(operatorStack.size() - 1);
}
if(isExit)
break;
}
}
}
}
逆波兰表达式(Java)
于 2021-05-18 16:54:39 首次发布