您的位置:首页 > 编程语言 > Java开发

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

2016-09-26 20:39 337 查看
中缀表达式转换为后缀表达式:

public static List<Object> convertFormula(List<Object> formula){
Stack<Object> operators = new Stack<Object>();
operators.push("#");
List<Object> out = new ArrayList<Object>();
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(wt1<wt2)
operators.push(o);
if(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<Object> pre){
double num1;
double num2;
double num = 0;
Stack<Object> nums = new Stack<Object>();
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<String,Integer> m;

static{
m = new HashMap<Stri
4000
ng,Integer>();
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;i<operators.length;i++){
if(T.equals(operators[i])){
flag = true;
break;
}
}
return flag;
}
else return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: