利用栈实现逆波兰表达式的转换与计算

import java.util.Scanner;
import java.util.Stack;


public class Calculator {

    //中序表达式转后续
    private static Stack interfixToSuffix(String expression) {

        Stack result = new Stack<>();
        Stack symbol = new Stack<>();

        char[] chars = expression.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char aChar = chars[i];
            if (isSymbol(aChar)) {
                if (symbol.empty()) {
                    symbol.push(aChar);
                } else if (getPrioraty(aChar) > getPrioraty(symbol.peek())) {
                    symbol.push(aChar);
                } else {
                    while (!symbol.empty() && getPrioraty(aChar) <= getPrioraty(symbol.peek())) {
                        result.push(symbol.pop());
                    }
                    symbol.push(aChar);
                }
            } else {
                result.push(aChar);
            }
        }
        while (!symbol.empty()) {
            result.push(symbol.pop());
        }
        return result;
    }
    //表达式符合优先级判断
    private static int getPrioraty(char value) {
        switch (value) {
            case '+':
            case '-':
                return 1;
            case '*':
            case '/':
                return 2;
            default:
                return 0;
        }
    }


    //计算后缀表达式
    private static int countSuffix(Stack suffix) {

        Stack suffix1 =  new Stack<>();

        while (!suffix.empty()){
            suffix1.push(suffix.pop());
        }

        Stack number = new Stack<>();

        while (!suffix1.empty()) {
            Character pop = suffix1.pop();
            if (!isSymbol(pop)) {
                number.push(Integer.valueOf(new String(new char[]{pop})));
            } else {
                Integer pop1 = number.pop();
                Integer pop2 = number.pop();
                number.push(depostNumber(pop1, pop2, pop));
            }
        }
        return number.pop();
    }


    private static int depostNumber(int pop, int i, char c) {
        switch (c) {
            case '+':
                return pop + i;
            case '-':
                return pop - i;
            case '*':
                return pop * i;
            case '/':
                return pop / i;

        }
        throw new RuntimeException("异常符号");
    }

    //判断是否为符号
    private static boolean isSymbol(char c) {
        return c == '+' || c == '-' || c == '/' || c == '*' || c == '(' || c == ')';
    }



    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String next = scanner.next();

        Stack suffix = interfixToSuffix(next);
        System.out.println(suffix);
        System.out.println(countSuffix(suffix));

    }
}

你可能感兴趣的:(java,逆波兰表达式,四则运算)