package three;
import java.util.Stack;
import java.util.StringTokenizer;
public class CalcStack {
public static void main(String[] args) {
String content = "30-5*(3/7-20)";
String content1 = "1 + 5 * 6 + 3 * (2 + 3*2+2-1+3*3) + 10/5 - 6*1";
String content2 = "3 * ( 2+ 3*2+2-1+3*3)";
System.out.println(content + " = " + postfixExpression(content));
System.out.println(content1 + " = " + postfixExpression(content1));
System.out.println(content2 + " = " + postfixExpression(content2));
}
public static String postfixExpression(String content) {
// 用于存储操作符的栈
Stack<String> stack = new Stack<String>();
// 将传入的表达式通过+-*/()分割,后面的true参数是保留分割符
StringTokenizer s = new StringTokenizer(content.replace(" ", ""), "+-*/()", true);
String result = "";
while (s.hasMoreElements()) {
char[] current = (s.nextToken()).toCharArray();
String next = "";
switch (current[0]) {
case '+':
if (!stack.isEmpty())
// 如果上一个操作符是+或-号,则上一操作符出栈并记录于result中
if (!stack.isEmpty()
&& (stack.peek().equals("+") || stack.peek()
.equals("-"))) {
result += " " + stack.pop();
}
// 当前操作符入栈
stack.push(String.valueOf(current));
break;
case '-':
if (!stack.isEmpty())
// 如果上一个操作符是+或-号,则上一操作符出栈并记录于result中
if (stack.peek().equals("+") || stack.peek().equals("-")) {
result += " " + stack.pop();
}
// 当前操作符入栈
stack.push(String.valueOf(current));
break;
case '*':
next = s.nextToken(); // 取下一个待处理的串
// 如果下一个操作符不是左括号,则执行以下操作
if (!next.equals("(")) {
result += " " + next + " *";
} else { // 否则当前操作符*和(入栈
stack.push(String.valueOf(current));
stack.push(next);
}
break;
case '/':
next = s.nextToken(); // 取下一个待处理的串
// 如果下一个操作符不是左括号,则执行以下操作
if (!next.equals("(")) {
result += " " + next + " /";
} else {// 否则当前操作符/和(入栈
stack.push(String.valueOf(current));
stack.push(next);
}
break;
case '(':
// 否则当前)入栈
stack.push(String.valueOf(current));
break;
case ')':
if(stack.size()>=2) {
result += " " + stack.pop(); // 上一操作符出栈
stack.pop(); // 左括号出栈
}
while (!stack.isEmpty()) {
String t = stack.pop();
if(t.equals("(")) { //如果是内括号的左括号,则停止输出栈内的运算符
stack.push(t);
break;
}
result += " " + t;
}
break;
default:
// 当前的字符串是数字直接输出
result += " " + String.valueOf(current);
break;
}
}
// 如果栈不为空,则输出剩下的操作符
while (!stack.isEmpty()) {
result += " " + stack.pop();
}
return result;
}
}
结果:
30-5*(3/7-20) = 30 5 3 7 / 20 - * -
1 + 5 * 6 + 3 * (2 + 3*2+2-1+3*3) + 10/5 - 6*1 = 1 5 6 * + 3 2 3 2 * + 2 + 1 - 3 3 * + 10 5 / + 6 1 * - * +
3 * ( 2+ 3*2+2-1+3*3) = 3 2 3 2 * + 2 + 1 - 3 3 * + *