Java版 中缀表达式转换为后缀表达式并求结果

基础知识

平时我们所说的一个算术表达式,例如:9+(3-1)*3+10/2即为中缀表达式,然而计算机无法计算中缀表达式的值,这是因为计算机无法进行带有左右括号和运算符的优先级这种混合运算。后缀表达式(又称 逆波兰式)的使用解决了上述问题。
上述的算术表达式的后缀表达式为:9 3 1 - 3 * + 10 2 / +

算法思想

如何计算上述后缀表达式的结果呢?
答案:从左到右扫描上述后缀表达式,然后:
1. 遇到数字入栈
2. 遇到运算符 将栈顶的前两个元素出栈,然后计算结果,并将计算的结果入栈
3. 重复1、2两步直到栈中只有一个元素即为最终结果

事例代码

以 中缀表达式:9+(3-1)*3+10/2 为例

求后缀表达式及最终结果代码:

import java.util.ArrayList;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 求后缀表达式及运算结果
 */
public class Operators {
    public ArrayList<String> getHouZuiBDS(String expression) {
        // 如将中缀表达式:9+(3-1)*3+10/2转化为后缀表达式9 3 1 - 3 * + 10 2 / +
        // 思路:一个运算符栈s,遇到数字就输出,而遇到操作符就有条件的进栈
        // 若当前运算符的优先级比栈顶元素高则进栈,否则出栈。然后在将当前操作符进栈
        // 但遇到右括号时以此将栈中元素出栈直到匹配到第一个左括号为止
        Stack<String> expStack = new Stack<String>();
        ArrayList<String> newExp = new ArrayList<String>();
        //在输入的字符串中,在每个字符间插入一个空格便于区分一位数和多位数
        String[] split = expression.split(" ");
        for (int i = 0; i < split.length; i++) {
            String s = split[i];
            if ("(".equals(s)) {
                expStack.push(s);
            } else if (")".equals(s)) {
                String pop;
                while (!expStack.isEmpty()) {
                    pop = expStack.pop();
                    if (pop.equals("(")) {
                        break;
                    } else {
                        newExp.add(pop);
                    }
                }
            } else if ("+".equals(s) || "-".equals(s) || "*".equals(s)
                    || "/".equals(s)) {
                if (expStack.isEmpty()) {
                    expStack.push(s);
                } else {
                    String top = expStack.peek();
                    if (comparePro(s, top)) {
                        // 当前输入的运算符s优先级高于栈顶运算符top的优先级,s入栈
                        expStack.push(s);
                    } else {
                        // 当前输入的运算符s优先级不高于栈顶运算符top的优先级,将比s优先级低或等于的出栈
                        while (!expStack.isEmpty()) {
                            String pop = expStack.peek();
                            if (!comparePro(s, pop)) {
                                newExp.add(expStack.pop());
                            } else {
                                break;
                            }
                        }
                        expStack.push(s);
                    }
                }
            } else {
                // 纯数字
                newExp.add(s);
            }
        }
        while (!expStack.isEmpty()) {
            newExp.add(expStack.pop());
        }
        return newExp;
    }

    /**
     * 比较优先级,若inputOper优先级小于等与sTopOperator返回false,大于返回true
     * 
     * @param inputOper
     *           输入运算符
     * @param sTopOperator
     *            栈顶运算符
     */
    public boolean comparePro(String inputOper, String sTopOperator) {
    //如果栈顶运算符为最括号,直接将输入运算符压栈
        if ("(".equals(sTopOperator)) {
            return true;
        }
        // 如果当前输入的操作运算符为“+”或“-”,并且栈顶运算符为“*”或“/”时,输入的运算符优先级大
        if (("*".equals(inputOper) || "/".equals(inputOper))
                && ("+".equals(sTopOperator) || "-".equals(sTopOperator))) {
            return true;
        }
        return false;
    }
/**
*根据中缀表达式计算最终结果
*/
    public int getResult(ArrayList<String> expression) {
        Stack<Integer> resStack = new Stack<Integer>();
        for (String str : expression) {
            if (str.matches("\\d+")) {
                resStack.push(Integer.valueOf(str));
            } else {
                if (resStack.isEmpty()) {
                    return -1;
                }
                // 栈不空,取出栈中前两个元素
                int tem1 = resStack.pop();
                int tem2 = resStack.pop();
                int temRes = 0;
                switch (str) {
                case "+":
                    temRes = tem2 + tem1;
                    break;

                case "-":
                    temRes = tem2 - tem1;
                    break;
                case "*":
                    temRes = tem2 * tem1;
                    break;
                case "/":
                    temRes = tem2 / tem1;
                    break;
                }
                resStack.push(temRes);
            }
        }
        if (resStack.size() == 1) {
            return resStack.pop();
        } else {
            return -1;
        }
    }
}

主函数代码:

package 后缀表达式;

import java.util.ArrayList;

/**
 * 后缀表达式
 */
public class Compute {

    public static void main(String[] args) {
        Operators op = new Operators();
        String expression = "9 + ( 3 - 1 ) * 3 + 10 / 2";
        ArrayList<String> res = op.getHouZuiBDS(expression);
        System.out.print("后缀表达式:");
        for (String string : res) {
            System.out.print(string+" ");
        }
        int result = op.getResult(res);
        System.out.println();
        System.out.println("计算结果:"+result);
    }
}

结果:

后缀表达式:9 3 1 - 3 * + 10 2 / +
计算结果:20

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值