import java.util.Stack;
//计算中缀表达式
//1+2*(3-4)+5
public class Test1 {
/**
* 后缀表达式计算
* @param expstr
* @return
*/
public static String toPostfix(String expstr){
String postfix="";
Stack<String> stack = new Stack<String>();
int i=0;
int explength=expstr.length();//字符串的长度
while (i<explength) {
char ch = expstr.charAt(i);
switch (ch) {
case '+':
case '-':
while (!stack.empty()&&!stack.peek().equals("(")) {
postfix+=stack.pop();
//如果栈非空,并且栈的栈顶不是“左括号”,也就是栈顶优先级>=该操作符的优先级出栈,添加到后缀表达式中
}
stack.push(ch+"");//将该操作符入栈
i++;
break;
case '*':
case '/':
while (!stack.empty()&&(stack.peek().equals("*")||stack.peek().equals("/"))) {
postfix+=stack.pop();
}
stack.push(ch+"");
i++;
break;
case '(':
stack.push("(");//左括号直接入栈
i++;
break;
case ')':
String out = stack.pop();//右括号出栈
while (out!=null&&!out.equals("(")) {
//如果出的不是null,并且不是左括号
postfix+=out;//添加到后缀表达式
out=stack.pop();
}
i++;
break;
default:
while (i<explength&&ch>='0'&&ch<='9') {
postfix+=ch;
i++;
if (i<explength) {
ch=expstr.charAt(i);
}
}
postfix+=" "; //以空格为分隔符
}
}
while (!stack.empty()) {
postfix+=stack.pop();
}
return postfix;
}
//计算后缀表达式
public static int value(String postfix){
int result=0;
int len = postfix.length();
Stack<Integer> stack = new Stack<Integer>();
int i=0;
while (i<len) {
char ch = postfix.charAt(i);
if (ch>='0'&&ch<='9') {
result = 0;
while (ch!=' ') {//上面的后缀表达式以空格为分隔符
result = result*10+Integer.parseInt(ch+"");
//如果不是空格的话,就计算该数。比如 123 456 +。
i++;
ch=postfix.charAt(i);
}//
i++;
stack.push(result);//将操作数压栈
}else{
int y = stack.pop().intValue();
int x = stack.pop().intValue();
switch (ch) {
case '+':
result = x+y ;
break;
case '-':
result = x-y ;
break;
case '*':
result = x*y ;
break;
case '/':
result = x/y ;
break;
}
stack.push(new Integer(result));
i++;
}
}
return stack.pop().intValue();
}
}