中綴表達(dá)式轉(zhuǎn)后綴表達(dá)式的方法:
- 遇到操作數(shù):直接輸出(添加到后綴表達(dá)式中)
- 棧為空時(shí)箍铭,遇到運(yùn)算符,直接入棧
- 遇到左括號(hào):將其入棧
- 遇到右括號(hào):執(zhí)行出棧操作蜜唾,并將出棧的元素輸出杂曲,直到彈出棧的是左括號(hào)箕昭,左括號(hào)不輸出。
- 遇到其他運(yùn)算符:加減乘除:彈出所有優(yōu)先級(jí)大于或者等于該運(yùn)算符的棧頂元素解阅,然后將該運(yùn)算符入棧
- 最終將棧中的元素依次出棧,輸出泌霍。
輸入是用space分割的expression货抄,數(shù)字可以是negative number,不用處理括號(hào)
public class EvalExpression {
public static void main(String[] args) {
String exp = "6 / 3 / 2";
int res = eval(exp);
System.out.println(res);
}
static int eval(String exp) {
String[] tokens = exp.split(" ");
Stack<Integer> nums = new Stack<Integer>();
Stack<String> operators = new Stack<String>();
Set<String> operand = new HashSet<String>();
operand.add("+");
operand.add("-");
operand.add("*");
operand.add("/");
for (String token : tokens) {
if (operand.contains(token)) {
if (operators.isEmpty()) {
operators.push(token);
}
else {
if (token.equals("+") || token.equals("-")) {
while (! operators.isEmpty()) {
String tmp = operators.pop();
int num2 = nums.pop(), num1 = nums.pop();
nums.push(operate(num1, num2, tmp));
}
}
if (token.equals("*") || token.equals("/")) {
while (! operators.isEmpty() && (operators.peek().equals("*") || operators.peek().equals("/"))) {
String tmp = operators.pop();
int num2 = nums.pop(), num1 = nums.pop();
nums.push(operate(num1, num2, tmp));
}
}
operators.push(token);
}
}
else {
nums.push(Integer.parseInt(token));
}
}
while (! operators.isEmpty()) {
String tmp = operators.pop();
int num2 = nums.pop(), num1 = nums.pop();
nums.push(operate(num1, num2, tmp));
}
return nums.pop();
}
}