前、中、後綴表達式

原文地址:http://blog.csdn.net/antineutrino/article/details/6763722


它們都是對表達式的記法,因此也被稱爲前綴記法、中綴記法和後綴記法。它們之間的區別在於運算符相對與操作數的位置不同:前綴表達式的運算符位於與其相關的操作數之前;中綴和後綴同理。


舉例:
(3 + 4) × 5 - 6 就是中綴表達式
- × + 3 4 5 6 前綴表達式
3 4 + 5 × 6 - 後綴表達式

中綴表達式(中綴記法)
中綴表達式是一種通用的算術或邏輯公式表示方法,操作符以中綴形式處於操作數的中間。中綴表達式是人們常用的算術表示方法。
雖然人的大腦很容易理解與分析中綴表達式,但對計算機來說中綴表達式卻是很複雜的,因此計算表達式的值時,通常需要先將中綴表達式轉換爲前綴或後綴表達式,然後再進行求值。對計算機來說,計算前綴或後綴表達式的值非常簡單。

前綴表達式(前綴記法、波蘭式)
前綴表達式的運算符位於操作數之前。

前綴表達式的計算機求值:
從右至左掃描表達式,遇到數字時,將數字壓入堆棧,遇到運算符時,彈出棧頂的兩個數,用運算符對它們做相應的計算(棧頂元素 op 次頂元素),並將結果入棧;重複上述過程直到表達式最左端,最後運算得出的值即爲表達式的結果。
例如前綴表達式“- × + 3 4 5 6”:
(1) 從右至左掃描,將6、5、4、3壓入堆棧;
(2) 遇到+運算符,因此彈出3和4(3爲棧頂元素,4爲次頂元素,注意與後綴表達式做比較),計算出3+4的值,得7,再將7入棧;
(3) 接下來是×運算符,因此彈出7和5,計算出7×5=35,將35入棧;
(4) 最後是-運算符,計算出35-6的值,即29,由此得出最終結果。
可以看出,用計算機計算前綴表達式的值是很容易的。

將中綴表達式轉換爲前綴表達式:
遵循以下步驟:
(1) 初始化兩個棧:運算符棧S1和儲存中間結果的棧S2;
(2) 從右至左掃描中綴表達式;
(3) 遇到操作數時,將其壓入S2;
(4) 遇到運算符時,比較其與S1棧頂運算符的優先級:
(4-1) 如果S1爲空,或棧頂運算符爲右括號“)”,則直接將此運算符入棧;
(4-2) 否則,若優先級比棧頂運算符的較高或相等,也將運算符壓入S1;
(4-3) 否則,將S1棧頂的運算符彈出並壓入到S2中,再次轉到(4-1)與S1中新的棧頂運算符相比較;
(5) 遇到括號時:
(5-1) 如果是右括號“)”,則直接壓入S1;
(5-2) 如果是左括號“(”,則依次彈出S1棧頂的運算符,並壓入S2,直到遇到右括號爲止,此時將這一對括號丟棄;
(6) 重複步驟(2)至(5),直到表達式的最左邊;
(7) 將S1中剩餘的運算符依次彈出並壓入S2;
(8) 依次彈出S2中的元素並輸出,結果即爲中綴表達式對應的前綴表達式。
例如,將中綴表達式“1+((2+3)×4)-5”轉換爲前綴表達式的過程如下:
掃描到的元素 S2(棧底->棧頂) S1 (棧底->棧頂) 說明
5 5 數字,直接入棧
- 5 - S1爲空,運算符直接入棧
) 5 - ) 右括號直接入棧
4 5 4 - ) 數字直接入棧
× 5 4 - ) × S1棧頂是右括號,直接入棧
) 5 4 - ) × ) 右括號直接入棧
3 5 4 3 - ) × ) 數字
+ 5 4 3 - ) × ) + S1棧頂是右括號,直接入棧
2 5 4 3 2 - ) × ) + 數字
( 5 4 3 2 + - ) × 左括號,彈出運算符直至遇到右括號
( 5 4 3 2 + × - 同上
+ 5 4 3 2 + × - + 優先級與-相同,入棧
1 5 4 3 2 + × 1 - + 數字
到達最左端 5 4 3 2 + × 1 + - S1中剩餘的運算符
因此結果爲“- + 1 × + 2 3 4 5”。

後綴表達式(後綴記法、逆波蘭式)
後綴表達式與前綴表達式類似,只是運算符位於操作數之後。

後綴表達式的計算機求值:
與前綴表達式類似,只是順序是從左至右:
從左至右掃描表達式,遇到數字時,將數字壓入堆棧,遇到運算符時,彈出棧頂的兩個數,用運算符對它們做相應的計算(次頂元素 op 棧頂元素),並將結果入棧;重複上述過程直到表達式最右端,最後運算得出的值即爲表達式的結果。
例如後綴表達式“3 4 + 5 × 6 -”:
(1) 從左至右掃描,將3和4壓入堆棧;
(2) 遇到+運算符,因此彈出4和3(4爲棧頂元素,3爲次頂元素,注意與前綴表達式做比較),計算出3+4的值,得7,再將7入棧;
(3) 將5入棧;
(4) 接下來是×運算符,因此彈出5和7,計算出7×5=35,將35入棧;
(5) 將6入棧;
(6) 最後是-運算符,計算出35-6的值,即29,由此得出最終結果。

將中綴表達式轉換爲後綴表達式:
與轉換爲前綴表達式相似,遵循以下步驟:
(1) 初始化兩個棧:運算符棧S1和儲存中間結果的棧S2;
(2) 從左至右掃描中綴表達式;
(3) 遇到操作數時,將其壓入S2;
(4) 遇到運算符時,比較其與S1棧頂運算符的優先級:
(4-1) 如果S1爲空,或棧頂運算符爲左括號“(”,則直接將此運算符入棧;
(4-2) 否則,若優先級比棧頂運算符的高,也將運算符壓入S1(注意轉換爲前綴表達式時是優先級較高或相同,而這裏則不包括相同的情況);
(4-3) 否則,將S1棧頂的運算符彈出並壓入到S2中,再次轉到(4-1)與S1中新的棧頂運算符相比較;
(5) 遇到括號時:
(5-1) 如果是左括號“(”,則直接壓入S1;
(5-2) 如果是右括號“)”,則依次彈出S1棧頂的運算符,並壓入S2,直到遇到左括號爲止,此時將這一對括號丟棄;
(6) 重複步驟(2)至(5),直到表達式的最右邊;
(7) 將S1中剩餘的運算符依次彈出並壓入S2;
(8) 依次彈出S2中的元素並輸出,結果的逆序即爲中綴表達式對應的後綴表達式(轉換爲前綴表達式時不用逆序)。

例如,將中綴表達式“1+((2+3)×4)-5”轉換爲後綴表達式的過程如下:
掃描到的元素 S2(棧底->棧頂) S1 (棧底->棧頂) 說明
1 1 數字,直接入棧
+ 1 + S1爲空,運算符直接入棧
( 1 + ( 左括號,直接入棧
( 1 + ( ( 同上
2 1 2 + ( ( 數字
+ 1 2 + ( ( + S1棧頂爲左括號,運算符直接入棧
3 1 2 3 + ( ( + 數字
) 1 2 3 + + ( 右括號,彈出運算符直至遇到左括號
× 1 2 3 + + ( × S1棧頂爲左括號,運算符直接入棧
4 1 2 3 + 4 + ( × 數字
) 1 2 3 + 4 × + 右括號,彈出運算符直至遇到左括號
- 1 2 3 + 4 × + - -與+優先級相同,因此彈出+,再壓入-
5 1 2 3 + 4 × + 5 - 數字
到達最右端 1 2 3 + 4 × + 5 - S1中剩餘的運算符

因此結果爲“1 2 3 + 4 × + 5 -”(注意需要逆序輸出)。

編寫Java程序將一箇中綴表達式轉換爲前綴表達式和後綴表達式,並計算表達式的值。其中的toPolishNotation()方法將中綴表達式轉換爲前綴表達式(波蘭式)、toReversePolishNotation()方法則用於將中綴表達式轉換爲後綴表達式(逆波蘭式):

注:
(1) 程序很長且註釋比較少,但如果將上面的理論內容弄懂之後再將程序編譯並運行起來,還是比較容易理解的。有耐心的話可以研究一下。(2) 此程序是筆者爲了說明上述概念而編寫,僅做了簡單的測試,不保證其中沒有Bug,因此不要將其用於除研究之外的其他場合。


[java] view plaincopy
  1. package qmk.simple_test;  
  2. import java.util.Scanner;  
  3. import java.util.Stack;  
  4. /** 
  5.  * Example of converting an infix-expression to 
  6.  * Polish Notation (PN) or Reverse Polish Notation (RPN). 
  7.  * Written in 2011-8-25 
  8.  * @author QiaoMingkui 
  9.  */  
  10. public class Calculator {  
  11.       public static final String USAGE = "== usage ==\n"  
  12.             + "input the expressions, and then the program "  
  13.             + "will calculate them and show the result.\n"  
  14.             + "input 'bye' to exit.\n";  
  15.       /** 
  16.        * @param args 
  17.        */  
  18.       public static void main(String[] args) {  
  19.             System.out.println(USAGE);  
  20.             Scanner scanner = new Scanner(System.in);  
  21.             String input = "";  
  22.             final String CLOSE_MARK = "bye";  
  23.             System.out.println("input an expression:");  
  24.             input = scanner.nextLine();  
  25.             while (input.length() != 0  
  26.                   && !CLOSE_MARK.equals((input))) {  
  27.                   System.out.print("Polish Notation (PN):");  
  28.                   try {  
  29.                         toPolishNotation(input);  
  30.                   } catch (NumberFormatException e) {  
  31.                         System.out.println("\ninput error, not a number.");  
  32.                   } catch (IllegalArgumentException e) {  
  33.                         System.out.println("\ninput error:" + e.getMessage());  
  34.                   } catch (Exception e) {  
  35.                         System.out.println("\ninput error, invalid expression.");  
  36.                   }  
  37.                   System.out.print("Reverse Polish Notation (RPN):");  
  38.                   try {  
  39.                         toReversePolishNotation(input);  
  40.                   } catch (NumberFormatException e) {  
  41.                         System.out.println("\ninput error, not a number.");  
  42.                   } catch (IllegalArgumentException e) {  
  43.                         System.out.println("\ninput error:" + e.getMessage());  
  44.                   } catch (Exception e) {  
  45.                         System.out.println("\ninput error, invalid expression.");  
  46.                   }  
  47.                   System.out.println("input a new expression:");  
  48.                   input = scanner.nextLine();  
  49.             }  
  50.             System.out.println("program exits");  
  51.       }  
  52.       /** 
  53.        * parse the expression , and calculate it. 
  54.        * @param input 
  55.        * @throws IllegalArgumentException 
  56.        * @throws NumberFormatException 
  57.        */  
  58.       private static void toPolishNotation(String input)  
  59.                   throws IllegalArgumentException, NumberFormatException {  
  60.             int len = input.length();  
  61.             char c, tempChar;  
  62.             Stack<Character> s1 = new Stack<Character>();  
  63.             Stack<Double> s2 = new Stack<Double>();  
  64.             Stack<Object> expression = new Stack<Object>();  
  65.             double number;  
  66.             int lastIndex = -1;  
  67.             for (int i=len-1; i>=0; --i) {  
  68.                   c = input.charAt(i);  
  69.                   if (Character.isDigit(c)) {  
  70.                         lastIndex = readDoubleReverse(input, i);  
  71.                         number = Double.parseDouble(input.substring(lastIndex, i+1));  
  72.                         s2.push(number);  
  73.                         i = lastIndex;  
  74.                         if ((int) number == number)  
  75.                               expression.push((int) number);  
  76.                         else  
  77.                               expression.push(number);  
  78.                   } else if (isOperator(c)) {  
  79.                         while (!s1.isEmpty()  
  80.                                     && s1.peek() != ')'  
  81.                                     && priorityCompare(c, s1.peek()) < 0) {  
  82.                               expression.push(s1.peek());  
  83.                               s2.push(calc(s2.pop(), s2.pop(), s1.pop()));  
  84.                         }  
  85.                         s1.push(c);  
  86.                   } else if (c == ')') {  
  87.                         s1.push(c);  
  88.                   } else if (c == '(') {  
  89.                         while ((tempChar=s1.pop()) != ')') {  
  90.                               expression.push(tempChar);  
  91.                               s2.push(calc(s2.pop(), s2.pop(), tempChar));  
  92.                               if (s1.isEmpty()) {  
  93.                                     throw new IllegalArgumentException(  
  94.                                           "bracket dosen't match, missing right bracket ')'.");  
  95.                               }  
  96.                         }  
  97.                   } else if (c == ' ') {  
  98.                         // ignore  
  99.                   } else {  
  100.                         throw new IllegalArgumentException(  
  101.                                     "wrong character '" + c + "'");  
  102.                   }  
  103.             }  
  104.             while (!s1.isEmpty()) {  
  105.                   tempChar = s1.pop();  
  106.                   expression.push(tempChar);  
  107.                   s2.push(calc(s2.pop(), s2.pop(), tempChar));  
  108.             }  
  109.             while (!expression.isEmpty()) {  
  110.                   System.out.print(expression.pop() + " ");  
  111.             }  
  112.             double result = s2.pop();  
  113.             if (!s2.isEmpty())  
  114.                   throw new IllegalArgumentException("input is a wrong expression.");  
  115.             System.out.println();  
  116.             if ((int) result == result)  
  117.                   System.out.println("the result is " + (int) result);  
  118.             else  
  119.                   System.out.println("the result is " + result);  
  120.       }  
  121.       /** 
  122.        * parse the expression, and calculate it. 
  123.        * @param input 
  124.        * @throws IllegalArgumentException 
  125.        * @throws NumberFormatException 
  126.        */  
  127.       private static void toReversePolishNotation(String input)  
  128.                   throws IllegalArgumentException, NumberFormatException {  
  129.             int len = input.length();  
  130.             char c, tempChar;  
  131.             Stack<Character> s1 = new Stack<Character>();  
  132.             Stack<Double> s2 = new Stack<Double>();  
  133.             double number;  
  134.             int lastIndex = -1;  
  135.             for (int i=0; i<len; ++i) {  
  136.                   c = input.charAt(i);  
  137.                   if (Character.isDigit(c) || c == '.') {  
  138.                         lastIndex = readDouble(input, i);  
  139.                         number = Double.parseDouble(input.substring(i, lastIndex));  
  140.                         s2.push(number);  
  141.                         i = lastIndex - 1;  
  142.                         if ((int) number == number)  
  143.                               System.out.print((int) number + " ");  
  144.                         else  
  145.                               System.out.print(number + " ");  
  146.                   } else if (isOperator(c)) {  
  147.                         while (!s1.isEmpty()  
  148.                                     && s1.peek() != '('  
  149.                                     && priorityCompare(c, s1.peek()) <= 0) {  
  150.                               System.out.print(s1.peek() + " ");  
  151.                               double num1 = s2.pop();  
  152.                               double num2 = s2.pop();  
  153.                               s2.push(calc(num2, num1, s1.pop()));  
  154.                         }  
  155.                         s1.push(c);  
  156.                   } else if (c == '(') {  
  157.                         s1.push(c);  
  158.                   } else if (c == ')') {  
  159.                         while ((tempChar=s1.pop()) != '(') {  
  160.                               System.out.print(tempChar + " ");  
  161.                               double num1 = s2.pop();  
  162.                               double num2 = s2.pop();  
  163.                               s2.push(calc(num2, num1, tempChar));  
  164.                               if (s1.isEmpty()) {  
  165.                                     throw new IllegalArgumentException(  
  166.                                           "bracket dosen't match, missing left bracket '('.");  
  167.                               }  
  168.                         }  
  169.                   } else if (c == ' ') {  
  170.                         // ignore  
  171.                   } else {  
  172.                         throw new IllegalArgumentException(  
  173.                                     "wrong character '" + c + "'");  
  174.                   }  
  175.             }  
  176.             while (!s1.isEmpty()) {  
  177.                   tempChar = s1.pop();  
  178.                   System.out.print(tempChar + " ");  
  179.                   double num1 = s2.pop();  
  180.                   double num2 = s2.pop();  
  181.                   s2.push(calc(num2, num1, tempChar));  
  182.             }  
  183.             double result = s2.pop();  
  184.             if (!s2.isEmpty())  
  185.                   throw new IllegalArgumentException("input is a wrong expression.");  
  186.             System.out.println();  
  187.             if ((int) result == result)  
  188.                   System.out.println("the result is " + (int) result);  
  189.             else  
  190.                   System.out.println("the result is " + result);  
  191.       }  
  192.       /** 
  193.        * calculate the two number with the operation. 
  194.        * @param num1 
  195.        * @param num2 
  196.        * @param op 
  197.        * @return 
  198.        * @throws IllegalArgumentException 
  199.        */  
  200.       private static double calc(double num1, double num2, char op)  
  201.                   throws IllegalArgumentException {  
  202.             switch (op) {  
  203.             case '+':  
  204.                   return num1 + num2;  
  205.             case '-':  
  206.                   return num1 - num2;  
  207.             case '*':  
  208.                   return num1 * num2;  
  209.             case '/':  
  210.                   if (num2 == 0throw new IllegalArgumentException("divisor can't be 0.");  
  211.                   return num1 / num2;  
  212.             default:  
  213.                   return 0// will never catch up here  
  214.             }  
  215.       }  
  216.       /** 
  217.        * compare the two operations' priority. 
  218.        * @param c 
  219.        * @param peek 
  220.        * @return 
  221.        */  
  222.       private static int priorityCompare(char op1, char op2) {  
  223.             switch (op1) {  
  224.             case '+'case '-':  
  225.                   return (op2 == '*' || op2 == '/' ? -1 : 0);  
  226.             case '*'case '/':  
  227.                   return (op2 == '+' || op2 == '-' ? 1 : 0);  
  228.             }  
  229.             return 1;  
  230.       }  
  231.       /** 
  232.        * read the next number (reverse) 
  233.        * @param input 
  234.        * @param start 
  235.        * @return 
  236.        * @throws IllegalArgumentException 
  237.        */  
  238.       private static int readDoubleReverse(String input, int start)  
  239.                   throws IllegalArgumentException {  
  240.             int dotIndex = -1;  
  241.             char c;  
  242.             for (int i=start; i>=0; --i) {  
  243.                   c = input.charAt(i);  
  244.                   if (c == '.') {  
  245.                         if (dotIndex != -1)  
  246.                               throw new IllegalArgumentException(  
  247.                                     "there have more than 1 dots in the number.");  
  248.                         else  
  249.                               dotIndex = i;  
  250.                   } else if (!Character.isDigit(c)) {  
  251.                         return i + 1;  
  252.                   } else if (i == 0) {  
  253.                         return 0;  
  254.                   }  
  255.             }  
  256.             throw new IllegalArgumentException("not a number.");  
  257.       }  
  258.         
  259.       /** 
  260.        * read the next number 
  261.        * @param input 
  262.        * @param start 
  263.        * @return 
  264.        * @throws IllegalArgumentException 
  265.        */  
  266.       private static int readDouble(String input, int start)  
  267.       throws IllegalArgumentException {  
  268.             int len = input.length();  
  269.             int dotIndex = -1;  
  270.             char c;  
  271.             for (int i=start; i<len; ++i) {  
  272.                   c = input.charAt(i);  
  273.                   if (c == '.') {  
  274.                         if (dotIndex != -1)  
  275.                               throw new IllegalArgumentException(  
  276.                               "there have more than 1 dots in the number.");  
  277.                         else if (i == len - 1)  
  278.                               throw new IllegalArgumentException(  
  279.                               "not a number, dot can't be the last part of a number.");  
  280.                         else  
  281.                               dotIndex = i;  
  282.                   } else if (!Character.isDigit(c)) {  
  283.                         if (dotIndex == -1 || i - dotIndex > 1)  
  284.                               return i;  
  285.                         else  
  286.                               throw new IllegalArgumentException(  
  287.                               "not a number, dot can't be the last part of a number.");  
  288.                   } else if (i == len - 1) {  
  289.                         return len;  
  290.                   }  
  291.             }  
  292.               
  293.             throw new IllegalArgumentException("not a number.");  
  294.       }  
  295.       /** 
  296.        * return true if the character is an operator. 
  297.        * @param c 
  298.        * @return 
  299.        */  
  300.       private static boolean isOperator(char c) {  
  301.             return (c=='+' || c=='-' || c=='*' || c=='/');  
  302.       }  
  303. }  


下面是程序運行結果(綠色爲用戶輸入):

== usage ==
input the expressions, and then the program will calculate them and show the result.
input 'bye' to exit.

input an expression:
3.8+5.3
Polish Notation (PN):+ 3.8 5.3
the result is 9.1
Reverse Polish Notation (RPN):3.8 5.3 +
the result is 9.1
input a new expression:
5*(9.1+3.2)/(1-5+4.88)
Polish Notation (PN):/ * 5 + 9.1 3.2 + - 1 5 4.88
the result is 69.88636363636364
Reverse Polish Notation (RPN):5 9.1 3.2 + * 1 5 - 4.88 + /
the result is 69.88636363636364
input a new expression:
1+((2+3)*4)-5
Polish Notation (PN):- + 1 * + 2 3 4 5
the result is 16
Reverse Polish Notation (RPN):1 2 3 + 4 * + 5 -
the result is 16
input a new expression:
bye
program exits
發佈了30 篇原創文章 · 獲贊 0 · 訪問量 9771
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章