/** * 将中缀表达式转化成后缀表达式 */ public List<String> toPostfixExpressionList(List<String> list) { //定义两个栈 Stack<String> s1 = new Stack<>(); List<String> s2 = new ArrayList<>(); //遍历list for (String item : list) { if (item.matches("\\d+")) { s2.add(item); } else if (item.equals("(")) { s1.push(item); } else if (item.equals(")")) { //如果是右括号)则一次弹出s1栈顶的运算符,并放到s2中,知道遇到左括号为止,并将这一对括号丢弃 while (!s1.peek().equals("(")) { s2.add(s1.pop()); } //将(弹出s1栈,清除小括号 s1.pop(); } else { //当item的优先级小于等于s1栈顶运算符,将s1栈顶的运算符弹出并加入到s2中,再次转到s1中新的栈运算符相比较 while (s1.size() != 0 && prioirty(s1.peek()) >= prioirty(item)) { s2.add(s1.pop()); } //还需要将item压入栈 s1.push(item); } } while (s1.size() != 0) { s2.add(s1.pop()); } return s2; }
//判断符号的优先级 public int prioirty(String oper) { int res = 0; switch (oper) { case "+": res = 1; break; case "-": res = 1; break; case "*": res = 2; break; case "/": res = 2; break; } return res; }