JAVA实现中缀表达式转换为后缀表达式并计算

中缀表达式转换为后缀表达式:

public static List convertFormula(List formula){
    Stack operators = new Stack();
    operators.push("#");
    List out = new ArrayList();
    for(Object o:formula){
        if(isOperator(o)){
            if(operators.isEmpty())
                operators.push(o);
            else{
                int wt1 = getOperatorWt((String)operators.peek(),"top");
                int wt2 = getOperatorWt((String)o,"out");
                while(wt1>wt2){
                    out.add(operators.peek());
                    operators.pop();
                    wt1 = getOperatorWt((String)operators.peek(),"top");
                }
                if(wt1if(wt1==wt2&&(!o.equals("#"))){
                    operators.pop();
                    continue;
                }
                if(o.equals("#"))
                    break;
            }
        }else out.add(o);
    }
    return out;
}

示例:输入[12.0, +, 0.0, * , 0.0, +, 1.2, #] , 输出[12.0, 0.0, 0.0, * , +, 1.2, +]

计算一个后缀表达式:
这里接收的后缀表达式是反的。如果按照上例应为[+, 1.2, +, *, 0.0, 0.0, 12.0]

private static double calculateStack(Stack pre){
    double num1;
    double num2;
    double num = 0;
    Stack nums = new Stack();
    while(!pre.isEmpty()){
        if(isOperator(pre.peek())){
            num2 = (Double)nums.peek();
            nums.pop();
            num1 = (Double)nums.peek();
            nums.pop();
            switch((String)pre.peek()){
                case "+":{num = num1 + num2;break;}
                case "-":{num = num1 - num2;break;}
                case "*":{num = num1*num2;break;}
                case "/":{num = num1/num2;break;}
                default:
            }
            nums.push(num);
            pre.pop();
        }
        else{
            nums.push(pre.peek());
            pre.pop();
        }
    }
    return (Double)nums.peek();
}

如果按照上例输出为13.2

private static Map m;

static{
    m = new HashMap();
    m.put("+top", 3);
    m.put("+out", 2);
    m.put("-top", 3);
    m.put("-out", 2);
    m.put("*top", 6);
    m.put("*out", 5);
    m.put("/top", 6);
    m.put("/out", 5);
    m.put("(top", 1);
    m.put("(out", 9);
    m.put(")top", 9);
    m.put(")out", 1);
    m.put("#top", 0);
    m.put("#out", 0);
}

public static int getOperatorWt(String operator,String location){
    return m.get(operator + location);
}

public static boolean isOperator(Object T){
    if(T.getClass().toString().equals("class java.lang.String")){
        boolean flag = false;
        String[] operators = {"+","-","*","/","(",")","#"};
        for(int i=0;ilength;i++){
            if(T.equals(operators[i])){
                flag = true;
                break;
            }       
        }
        return flag;
    }
    else return false;
}

你可能感兴趣的:(表达式的解析计算)