中綴表達式轉換為后綴表達式(Java)


中綴表達式轉換為后綴表達式(Java)

博客說明

文章所涉及的資料來自互聯網整理和個人總結,意在於個人學習和經驗匯總,如有什么地方侵權,請聯系本人刪除,謝謝!

步驟

  1. 初始化兩個棧:運算符棧 s1 和儲存中間結果的棧 s2

  2. 從左至右掃描中綴表達式

  3. 遇到操作數時,將其壓 s2

  4. 遇到運算符時,比較其與 s1 棧頂運算符的優先級:

    • 如果 s1 為空,或棧頂運算符為左括號“(”,則直接將此運算符入棧
    • 否則,若優先級比棧頂運算符的高,也將運算符壓入 s1;
    • 否則,將 s1 棧頂的運算符彈出並壓入到 s2 中,再次轉到(4-1)與 s1 中新的棧頂運算符相比較;
  5. 遇到括號時:

    • 如果是左括號“(”,則直接壓入 s1
    • 如果是右括號“)”,則依次彈出 s1 棧頂的運算符,並壓入 s2,直到遇到左括號為止,此時將這一對括號丟棄
  6. 重復步驟 2 至 5,直到表達式的最右邊

  7. 將 s1 中剩余的運算符依次彈出並壓入 s2

  8. 依次彈出 s2 中的元素並輸出,結果的逆序即為中綴表達式對應的后綴表達式

案例

將中綴表達式“1+((2+3)×4)-5”轉換為后綴表達式的過程如下

因此結果為 :"123+4 × +5 –"

image-20200622181152378

代碼

package stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author guizimo
 * @date 2020/4/6 12:25 下午
 */
public class PolandNotation {
    public static void main(String[] args) {
        //表達式
        String suffixExpression = "1+((2+3)*4)-5";
        //中綴表達式對應的List
        System.out.println("中綴表達式對應的List");
        List<String> infixExpressionList = toInfixExpressionList(suffixExpression);
        System.out.println(infixExpressionList);
        //后綴表達式對應的List
        System.out.println("后綴表達式對應的List");
        List<String> suffixExpressionList = parseSuffixExpressionList(infixExpressionList);
        System.out.println(suffixExpressionList);

        //計算逆波蘭表達式
        System.out.printf("suffixExpression=%d", calculate(suffixExpressionList));

    }

    public static List<String> parseSuffixExpressionList(List<String> ls) {
        //定義兩個棧
        Stack<String> s1 = new Stack<String>();  //符號棧
        List<String> s2 = new ArrayList<String>();  //結果

        for (String item : ls) {
            //如果是一個數
            if (item.matches("\\d+")) {
                s2.add(item);
            } else if (item.equals("(")) {
                s1.push(item);
            } else if (item.equals(")")) {
                while (!s1.peek().equals("(")) {
                    s2.add(s1.pop());
                }
                s1.pop();
            } else {
                while (s1.size() != 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item)) {
                    s2.add(s1.pop());
                }
                s1.push(item);
            }
        }
        while (s1.size() != 0) {
            s2.add(s1.pop());
        }
        return s2;
    }

    //將中綴表達式轉換成list
    public static List<String> toInfixExpressionList(String s) {
        List<String> ls = new ArrayList<String>();
        int i = 0;
        String str;  //多位數
        char c;
        do {
            //非數字
            if ((c = s.charAt(i)) < 48 || (c = s.charAt(i)) > 57) {
                ls.add("" + c);
                i++;
            } else { //數字,但是考慮到多位數
                str = "";
                while (i < s.length() && (c = s.charAt(i)) >= 48 && (c = s.charAt(i)) <= 57) {
                    str += c;
                    i++;
                }
                ls.add(str);
            }
        } while (i < s.length());
        return ls;
    }

    //完成對逆波蘭表達式的計算
    public static int calculate(List<String> ls) {
        Stack<String> stack = new Stack<>();
        for (String item : ls) {
            //使用正則表達式
            if (item.matches("\\d+")) {  //匹配多位數
                //入棧
                stack.push(item);
            } else {
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(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("運算符有問題");
                }
                //把結果入棧
                stack.push("" + res);
            }
        }
        return Integer.parseInt(stack.pop());
    }
}


class Operation {
    private static int ADD = 1;
    private static int SUB = 1;
    private static int MUL = 2;
    private static int DIV = 2;

    public static int getValue(String operation) {
        int result = 0;
        switch (operation) {
            case "+":
                result = ADD;
                break;
            case "-":
                result = SUB;
                break;
            case "*":
                result = MUL;
                break;
            case "/":
                result = DIV;
                break;
            default:
                System.out.println("不存在");
                break;
        }
        return result;
    }
}

感謝

尚硅谷

萬能的網絡

以及勤勞的自己
關注公眾號: 歸子莫,獲取更多的資料,還有更長的學習計划


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM