利用stack实现四则运算表达式
1) a+b*c+(d*e+f)*g,输出:abc*+de*f+g*+
2) X=A+B*(C-D)/E , 输出:XABCD-*E/+=
/**
* @Title: InfixPostfix.java
* @Package stack
* @Description: TODO
* @author peidong
* @date 2017-5-4 上午8:47:51
* @version V1.0
*/
package stack;
import java.util.Stack;
public class InfixPostfix {
/**
*
* @Title: isOperand
* @Description: 判断字符ch是否是一个操作数
* @param @param ch
* @param @return
* @return boolean
* @throws
*/
public static boolean isOperand(char ch){
return (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z');
}
public static void infixToPostfix(String exp){
char expArr[] = exp.toCharArray();
Stack<Character> stack = new Stack<Character>();
//1.从做向右遍历表达式
for(int i =0; i <expArr.length; i++){
char ch = expArr[i];
//2.判断当前字符是否是操作数,然后打印
if(isOperand(ch)){
System.out.print(ch);
}//3.若当前字符为“(”则入栈
else if(ch == '('){ //注意此处要用单引号,双引号为字符串
stack.push(ch);
}//4.若当前字符为“)“,则出栈,直到栈为空或者弹出"("为止
else if(ch == ')'){
char top = stack.pop();
while(top != '('){
System.out.print(top);
top = stack.pop();
}
}
else{
int r = getRank(ch);
//5.比较操作符的优先级,当上一个操作符的优先级比操作符ch的优先级小或是栈为空则入栈
if(stack.isEmpty() || r > getRank(stack.peek())){
stack.push(ch);
}//6.否则不断弹出栈顶操作符并打印,知道栈为空或当前操作符ch的优先级大于栈顶的操作符,
//将当前操作符入栈
else{
while(!stack.isEmpty() && r <=getRank(stack.peek())){
System.out.print(stack.pop());
}
stack.push(ch);
}
}
}
//7.弹出并打印栈中剩余操作符
while(!stack.isEmpty()){
System.out.print(stack.pop());
}
System.out.println();
}
/**
*
* @Title: getRank
* @Description: 定义操作符的优先级
* @param @param ch
* @param @return
* @return int
* @throws
*/
public static int getRank(char ch){
switch(ch){
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
/**
* @Title: main
* @Description: 测试用例
* @param @param args
* @return void
* @throws
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String exp = "X=A+B*(C-D)/E";
infixToPostfix(exp);
String exp2 = "a+b*(c^d-e)^(f+g*h)-i";
infixToPostfix(exp2);
}
}