青之枫

中序表达式转换后序表达式

中序表达式
1、操作数就直接入栈 输出栈
2、操作符入操作符栈之前与栈顶操作符比较 如果当栈顶优先级高于或等于当前操作符,就出栈 进入输出栈
3、'('直接入栈操作符栈
4、')'出栈()之间的操作符 到输出栈

 

代码:

 

public String infixToPostfix(String str) throws InterruptedException {
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        map.put('+', 1);
        map.put('-', 1);
        map.put('*', 2);
        map.put('/', 2);
        map.put('(', 0);
        map.put(')', 0);
        Stack<String> dataStack = new Stack<String>();
        Stack<String> operatorStack = new Stack<String>();

        for (int i = 0; i < str.length(); i++) {
            char temp = str.charAt(i);
            if (isDigital(temp)) {
                if (dataStack.isEmpty()) {
                    dataStack.push("");
                }
                String data = dataStack.pop();
                dataStack.push(data + String.valueOf(temp));
            } else if (temp == '(') {
                operatorStack.push(String.valueOf(temp));
            } else if (temp == ')') {
                while (!operatorStack.peek().equals("(")) {
                    String oper = operatorStack.pop();
                    String data = dataStack.pop();
                    dataStack.push(data + oper);
                }
                operatorStack.pop();
            } else {
                while (!operatorStack.isEmpty()&&map.get(temp) <= map.get(operatorStack.peek().charAt(0))) {
                    String oper = operatorStack.pop();
                    String data = dataStack.pop();
                    dataStack.push(data + oper);

                }
                operatorStack.push(String.valueOf(temp));
            }

        }
        while (!operatorStack.isEmpty()) {
            String oper = operatorStack.pop();
            String data = dataStack.pop();
            dataStack.push(data + oper);
        }

        return dataStack.pop();
    }

 

posted on 2018-03-17 17:41  青之枫  阅读(3052)  评论(0编辑  收藏  举报

导航