中綴表達(dá)式轉(zhuǎn)后綴表達(dá)式并求值

copy的,供參考

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Poland {
        public static void main(String[] args) {
            String expression = "1+((2+3)*4)-5";
            List<String> expressionList = expressionToList(expression);
            System.out.println("中綴表達(dá)式轉(zhuǎn)為list結(jié)構(gòu)=" + expressionList);
            //將中綴表達(dá)式轉(zhuǎn)換為后綴表達(dá)式
            List<String> suffixList = parseToSuffixExpression(expressionList);
            System.out.println("對(duì)應(yīng)的后綴表達(dá)式列表結(jié)構(gòu)=" + suffixList);
            //根據(jù)后綴表達(dá)式計(jì)算結(jié)果
            int calculateResult = calculate(suffixList);
            System.out.printf(expression + "=%d\n", calculateResult);
        }
        
        private static List<String> expressionToList(String expression) {
            int index = 0;
            List<String> list = new ArrayList<>();
            do {
                char ch = expression.charAt(index);
                if (ch < '0' || ch > '9') {
                    //是操作符,直接添加至list中
                    index++;
                    list.add(ch + "");
                } else if (ch >= '0' && ch <= '9') {
                    //是數(shù)字,判斷多位數(shù)的情況
                    String str = "";
                    while (index < expression.length() && expression.charAt(index) >= '0' && expression.charAt(index) <= '9') {
                        str += expression.charAt(index);
                        index++;
                    }
                    list.add(str);
                }
            } while (index < expression.length());
            return list;
        }

        private static int calculate(List<String> list) {
            Stack<Integer> stack = new Stack<>();
            for (int i = 0; i < list.size(); i++) {
                String item = list.get(i);
                if (item.matches("\\d+")) {
                    //是數(shù)字
                    stack.push(Integer.parseInt(item));
                } else {
                    //是操作符,取出棧頂兩個(gè)元素
                    int num2 = stack.pop();
                    int num1 = stack.pop();
                    int res = 0;
                    if (item.equals("+")) {
                        res = num1 + num2;
                    } else if (item.equals("-")) {
                        res = num1 - num2;
                    } else if (item.equals("*")) {
                        res = num1 * num2;
                    } else if (item.equals("/")) {
                        res = num1 / num2;
                    } else {
                        throw new RuntimeException("運(yùn)算符錯(cuò)誤!");
                    }
                    stack.push(res);
                }
            }
            return stack.pop();
        }

        

        private static List<String> parseToSuffixExpression(List<String> expressionList) {
            //創(chuàng)建一個(gè)棧用于保存操作符
            Stack<String> opStack = new Stack<>();
            //創(chuàng)建一個(gè)list用于保存后綴表達(dá)式
            List<String> suffixList = new ArrayList<>();
            for (String item : expressionList) {
                //得到數(shù)或操作符
                if (isOperator(item)) {
                    //是操作符 判斷操作符棧是否為空
                    if (opStack.isEmpty() || "(".equals(opStack.peek()) || priority(item) > priority(opStack.peek())) {
                        //為空或者棧頂元素為左括號(hào)或者當(dāng)前操作符大于棧頂操作符直接壓棧
                        opStack.push(item);
                    } else {
                        //否則將棧中元素出棧如隊(duì),直到遇到大于當(dāng)前操作符或者遇到左括號(hào)時(shí)
                        while (!opStack.isEmpty() && !"(".equals(opStack.peek())) {
                            if (priority(item) <= priority(opStack.peek())) {
                                suffixList.add(opStack.pop());
                            }
                        }
                        //當(dāng)前操作符壓棧
                        opStack.push(item);
                    }
                } else if (isNumber(item)) {
                    //是數(shù)字則直接入隊(duì)
                    suffixList.add(item);
                } else if ("(".equals(item)) {
                    //是左括號(hào),壓棧
                    opStack.push(item);
                } else if (")".equals(item)) {
                    //是右括號(hào) ,將棧中元素彈出入隊(duì),直到遇到左括號(hào),左括號(hào)出棧,但不入隊(duì)
                    while (!opStack.isEmpty()) {
                        if ("(".equals(opStack.peek())) {
                            opStack.pop();
                            break;
                        } else {
                            suffixList.add(opStack.pop());
                        }
                    }
                } else {
                    throw new RuntimeException("有非法字符!");
                }
            }
            //循環(huán)完畢,如果操作符棧中元素不為空,將棧中元素出棧入隊(duì)
            while (!opStack.isEmpty()) {
                suffixList.add(opStack.pop());
            }
            return suffixList;
        }

        /**
         * 判斷字符串是否為操作符
         */
        public static boolean isOperator(String op) {
            return op.equals("+") || op.equals("-") || op.equals("*") || op.equals("/");
        }

        /**
         * 判斷是否為數(shù)字
         */
        public static boolean isNumber(String num) {
            return num.matches("\\d+");
        }

        /**
         * 獲取操作符的優(yōu)先級(jí)    
         */
        public static int priority(String op) {
            if (op.equals("*") || op.equals("/")) {
                return 1;
            } else if (op.equals("+") || op.equals("-")) {
                return 0;
            }
            return -1;
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容