import java.util.Scanner; import java.util.Stack; public class Calculator { //中序表达式转后续 private static Stack<Character> interfixToSuffix(String expression) { Stack<Character> result = new Stack<>(); Stack<Character> 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<Character> suffix) { Stack<Character> suffix1 = new Stack<>(); while (!suffix.empty()){ suffix1.push(suffix.pop()); } Stack<Integer> 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<Character> suffix = interfixToSuffix(next); System.out.println(suffix); System.out.println(countSuffix(suffix)); } }
利用栈实现逆波兰表达式的转换与计算
最新推荐文章于 2023-01-05 18:41:31 发布