数学表达式解析(前缀、中缀、后缀)_第1页
数学表达式解析(前缀、中缀、后缀)_第2页
数学表达式解析(前缀、中缀、后缀)_第3页
数学表达式解析(前缀、中缀、后缀)_第4页
数学表达式解析(前缀、中缀、后缀)_第5页
已阅读5页,还剩10页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、前缀、中缀、后缀表达式它们都是对表达式的记法,因此也被称为前缀记法、中缀记法和后缀记法。它们之间的区别在于运算符相对与操作数的位置不同:前缀表达式的运算符位于与其相关的操作数之前;中缀和后缀同理。举例:(3 + 4) × 5 - 6 就是中缀表达式- × + 3 4 5 6 前缀表达式3 4 + 5 × 6 - 后缀表达式中缀表达式(中缀记法)中缀表达式是一种通用的算术或逻辑公式表示方法,操作符以中缀形式处于操作数的中间。中缀表达式是人们常用的算术表示方法。虽然人的大脑很容易理解与分析中缀表达式,但对计算机来说中缀表达式却是很复杂的,因此计算表

2、达式的值时,通常需要先将中缀表达式转换为前缀或后缀表达式,然后再进行求值。对计算机来说,计算前缀或后缀表达式的值非常简单。前缀表达式(前缀记法、波兰式)前缀表达式的运算符位于操作数之前。前缀表达式的计算机求值:从右至左扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(栈顶元素 op 次顶元素),并将结果入栈;重复上述过程直到表达式最左端,最后运算得出的值即为表达式的结果。例如前缀表达式“- × + 3 4 5 6”:(1) 从右至左扫描,将6、5、4、3压入堆栈;(2) 遇到+运算符,因此弹出3和4(3为栈顶元素,4为次顶元素,注意与

3、后缀表达式做比较),计算出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) 否则,若优先级比栈顶

4、运算符的较高或相等,也将运算符压入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(

5、栈底->栈顶)S1 (栈底->栈顶)说明55空数字,直接入栈-5-S1为空,运算符直接入栈)5- )右括号直接入栈45 4- )数字直接入栈×5 4- ) ×S1栈顶是右括号,直接入栈)5 4- ) × )右括号直接入栈35 4 3- ) × )数字+5 4 3- ) × ) +S1栈顶是右括号,直接入栈25 4 3 2- ) × ) +数字(5 4 3 2 +- ) ×左括号,弹出运算符直至遇到右括号(5 4 3 2 + ×-同上+5 4 3 2 + ×- +优先级与-相同,入栈15 4 3

6、 2 + × 1- +数字到达最左端5 4 3 2 + × 1 + -空S1中剩余的运算符因此结果为“- + 1 × + 2 3 4 5”。后缀表达式(后缀记法、逆波兰式)后缀表达式与前缀表达式类似,只是运算符位于操作数之后。后缀表达式的计算机求值:与前缀表达式类似,只是顺序是从左至右:从左至右扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(次顶元素 op 栈顶元素),并将结果入栈;重复上述过程直到表达式最右端,最后运算得出的值即为表达式的结果。例如后缀表达式“3 4 + 5 × 6 -”:(

7、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) 遇到运算符时,比较其与

8、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中剩余的运算符

9、依次弹出并压入S2;(8) 依次弹出S2中的元素并输出,结果的逆序即为中缀表达式对应的后缀表达式(转换为前缀表达式时不用逆序)。例如,将中缀表达式“1+(2+3)×4)-5”转换为后缀表达式的过程如下:扫描到的元素S2(栈底->栈顶)S1 (栈底->栈顶)说明11空数字,直接入栈+1+S1为空,运算符直接入栈(1+ (左括号,直接入栈(1+ ( (同上21 2+ ( (数字+1 2+ ( ( +S1栈顶为左括号,运算符直接入栈31 2 3+ ( ( +数字)1 2 3 + (右括号,弹出运算符直至遇到左括号×1 2 3 + ( ×S1栈顶为左括号,运算

10、符直接入栈41 2 3 + 4+ ( ×数字)1 2 3 + 4 ×+右括号,弹出运算符直至遇到左括号-1 2 3 + 4 × +-与+优先级相同,因此弹出+,再压入-51 2 3 + 4 × + 5-数字到达最右端1 2 3 + 4 × + 5 -空S1中剩余的运算符因此结果为“1 2 3 + 4 × + 5 -”(注意需要逆序输出)。编写Java程序将一个中缀表达式转换为前缀表达式和后缀表达式,并计算表达式的值。其中的toPolishNotation()方法将中缀表达式转换为前缀表达式(波兰式)、toReversePolishNo

11、tation()方法则用于将中缀表达式转换为后缀表达式(逆波兰式):注:(1) 程序很长且注释比较少,但如果将上面的理论内容弄懂之后再将程序编译并运行起来,还是比较容易理解的。有耐心的话可以研究一下。(2) 此程序是笔者为了说明上述概念而编写,仅做了简单的测试,不保证其中没有Bug,因此不要将其用于除研究之外的其他场合。java view plain copy1. package qmk.simple_test;  2. import java.util.Scanner;  3. import java.

12、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.  *&#

13、160;author QiaoMingkui 9.  */  10. public class Calculator   11.       public static final String USAGE = "= usage =n"  12.       

14、      + "input the expressions, and then the program "  13.             + "will calculate them and show the re

15、sult.n"  14.             + "input 'bye' to exit.n"  15.       /* 16.        * param args 17.

16、        */  18.       public static void main(String args)   19.             System.out.println(USAGE);  20.   

17、;          Scanner scanner = new Scanner(System.in);  21.             String input = ""  22.      &#

18、160;      final String CLOSE_MARK = "bye"  23.             System.out.println("input an expression:");  24.      &#

19、160;      input = scanner.nextLine();  25.             while (input.length() != 0  26.              

20、     && !CLOSE_MARK.equals(input)   27.                   System.out.print("Polish Notation (PN):");  28.    

21、60;              try   29.                         toPolishNotation(input);  30. 

22、0;                  catch (NumberFormatException e)   31.                      &

23、#160;  System.out.println("ninput error, not a number.");  32.                    catch (IllegalArgumentException e)   33.  &

24、#160;                      System.out.println("ninput error:" + e.getMessage();  34.            

25、0;       catch (Exception e)   35.                         System.out.println("ninput error, invalid 

26、;expression.");  36.                     37.                   System.out.print("Reverse&#

27、160;Polish Notation (RPN):");  38.                   try   39.                   

28、;      toReversePolishNotation(input);  40.                    catch (NumberFormatException e)   41.       

29、60;                 System.out.println("ninput error, not a number.");  42.                 

30、60;  catch (IllegalArgumentException e)   43.                         System.out.println("ninput error:" + e.getMessage(

31、);  44.                    catch (Exception e)   45.                    

32、60;    System.out.println("ninput error, invalid expression.");  46.                     47.         

33、0;         System.out.println("input a new expression:");  48.                   input = scanner.nextLine();  

34、49.               50.             System.out.println("program exits");  51.         52.    

35、;   /* 53.        * parse the expression , and calculate it. 54.        * param input 55.        * throws Ille

36、galArgumentException 56.        * throws NumberFormatException 57.        */  58.       private static void toPolishNotation(String input)  

37、59.                   throws IllegalArgumentException, NumberFormatException   60.             int len = input

38、.length();  61.             char c, tempChar;  62.             Stack<Character> s1 = new Stack<Character>(); 

39、0;63.             Stack<Double> s2 = new Stack<Double>();  64.             Stack<Object> expression = new Stack&

40、lt;Object>();  65.             double number;  66.             int lastIndex = -1;  67.       

41、60;     for (int i=len-1; i>=0; -i)   68.                   c = input.charAt(i);  69.        

42、;           if (Character.isDigit(c)   70.                         lastIndex = readDoubleRevers

43、e(input, i);  71.                         number = Double.parseDouble(input.substring(lastIndex, i+1);  72.      &#

44、160;                  s2.push(number);  73.                         i =

45、0;lastIndex;  74.                         if (int) number = number)  75.            &

46、#160;                  expression.push(int) number);  76.                        

47、; else  77.                               expression.push(number);  78.          

48、;          else if (isOperator(c)   79.                         while (!s1.isEmpty()  80.

49、                                    && s1.peek() != ')'  81.    

50、                                 && priorityCompare(c, s1.peek() < 0)   82.   &

51、#160;                           expression.push(s1.peek();  83.                &

52、#160;              s2.push(calc(s2.pop(), s2.pop(), s1.pop();  84.                         

53、;  85.                         s1.push(c);  86.                   

54、0;else if (c = ')')   87.                         s1.push(c);  88.           

55、         else if (c = '(')   89.                         while (tempChar=s1.pop() 

56、!= ')')   90.                               expression.push(tempChar);  91.       

57、                        s2.push(calc(s2.pop(), s2.pop(), tempChar);  92.               

58、60;               if (s1.isEmpty()   93.                            &#

59、160;        throw new IllegalArgumentException(  94.                                &

60、#160;          "bracket dosen't match, missing right bracket ')'.");  95.                    

61、             96.                           97.          

62、0;         else if (c = ' ')   98.                         / ignore  99.

63、                    else   100.                         throw new

64、 IllegalArgumentException(  101.                                     "wrong character '

65、;" + c + "'");  102.                     103.               104.   

66、0;         while (!s1.isEmpty()   105.                   tempChar = s1.pop();  106.        

67、;           expression.push(tempChar);  107.                   s2.push(calc(s2.pop(), s2.pop(), tempChar);  108.   

68、            109.             while (!expression.isEmpty()   110.                 

69、;  System.out.print(expression.pop() + " ");  111.               112.             double result = s2.pop();

70、60; 113.             if (!s2.isEmpty()  114.                   throw new IllegalArgumentException("input is

71、60;a wrong expression.");  115.             System.out.println();  116.             if (int) result = result)  117.

72、                   System.out.println("the result is " + (int) result);  118.             else 

73、 119.                   System.out.println("the result is " + result);  120.         121.      

74、 /* 122.        * parse the expression, and calculate it. 123.        * param input 124.        * throws IllegalArgumentExcep

75、tion 125.        * throws NumberFormatException 126.        */  127.       private static void toReversePolishNotation(String input)  128. &

76、#160;                 throws IllegalArgumentException, NumberFormatException   129.             int len = input.len

77、gth();  130.             char c, tempChar;  131.             Stack<Character> s1 = new Stack<Character>();  

78、132.             Stack<Double> s2 = new Stack<Double>();  133.             double number;  134.     

79、60;       int lastIndex = -1;  135.             for (int i=0; i<len; +i)   136.           &#

80、160;       c = input.charAt(i);  137.                   if (Character.isDigit(c) | c = '.')   138.  &#

81、160;                      lastIndex = readDouble(input, i);  139.                 

82、60;       number = Double.parseDouble(input.substring(i, lastIndex);  140.                         s2.push(number); 

83、; 141.                         i = lastIndex - 1;  142.                

84、;         if (int) number = number)  143.                               Sys

85、tem.out.print(int) number + " ");  144.                         else  145.          &

86、#160;                    System.out.print(number + " ");  146.                  

87、  else if (isOperator(c)   147.                         while (!s1.isEmpty()  148.         

88、;                            && s1.peek() != '('  149.           

89、0;                         && priorityCompare(c, s1.peek() <= 0)   150.          

90、60;                    System.out.print(s1.peek() + " ");  151.                  

91、;             double num1 = s2.pop();  152.                            

92、0;  double num2 = s2.pop();  153.                               s2.push(calc(num2, num1, s1.pop(); &

93、#160;154.                           155.                      

94、60;  s1.push(c);  156.                    else if (c = '(')   157.             

95、60;           s1.push(c);  158.                    else if (c = ')')   159.    

96、60;                    while (tempChar=s1.pop() != '(')   160.                 

97、60;             System.out.print(tempChar + " ");  161.                         

98、      double num1 = s2.pop();  162.                               double num2 = 

99、s2.pop();  163.                               s2.push(calc(num2, num1, tempChar);  164.      &#

100、160;                        if (s1.isEmpty()   165.                   

101、                  throw new IllegalArgumentException(  166.                      

102、0;                    "bracket dosen't match, missing left bracket '('.");  167.          

103、60;                      168.                           169.

104、                    else if (c = ' ')   170.                   

105、0;     / ignore  171.                    else   172.                 &

106、#160;       throw new IllegalArgumentException(  173.                                 

107、;    "wrong character '" + c + "'");  174.                     175.        &#

108、160;      176.             while (!s1.isEmpty()   177.                   tempChar = s1.pop

109、();  178.                   System.out.print(tempChar + " ");  179.                 &

110、#160; double num1 = s2.pop();  180.                   double num2 = s2.pop();  181.             

111、;      s2.push(calc(num2, num1, tempChar);  182.               183.             double result = s2.pop();

112、  184.             if (!s2.isEmpty()  185.                   throw new IllegalArgumentException("input is

113、 a wrong expression.");  186.             System.out.println();  187.             if (int) result = result)  1

114、88.                   System.out.println("the result is " + (int) result);  189.             else

115、60; 190.                   System.out.println("the result is " + result);  191.         192.     

116、60; /* 193.        * calculate the two number with the operation. 194.        * param num1 195.        * param num2 

117、;196.        * param op 197.        * return 198.        * throws IllegalArgumentException 199.        */  200

118、.       private static double calc(double num1, double num2, char op)  201.                   throws IllegalArgumentException

119、   202.             switch (op)   203.             case '+':  204.          &

120、#160;        return num1 + num2;  205.             case '-':  206.               &

121、#160;   return num1 - num2;  207.             case '*':  208.                   return&

122、#160;num1 * num2;  209.             case '/':  210.                   if (num2 = 0) thr

123、ow new IllegalArgumentException("divisor can't be 0.");  211.                   return num1 / num2;  212.      

124、       default:  213.                   return 0; / will never catch up here  214.       &

125、#160;       215.         216.       /* 217.        * compare the two operations' priority. 218.     &

126、#160;  * param c 219.        * param peek 220.        * return 221.        */  222.       private st

127、atic int priorityCompare(char op1, char op2)   223.             switch (op1)   224.             case '+':&#

128、160;case '-':  225.                   return (op2 = '*' | op2 = '/' ? -1 : 0);  226.    

129、60;        case '*': case '/':  227.                   return (op2 = '+' | op2 = '

130、-' ? 1 : 0);  228.               229.             return 1;  230.         231. &#

131、160;     /* 232.        * read the next number (reverse) 233.        * param input 234.        * param start&#

132、160;235.        * return 236.        * throws IllegalArgumentException 237.        */  238.       private static int

133、0;readDoubleReverse(String input, int start)  239.                   throws IllegalArgumentException   240.          

134、60;  int dotIndex = -1;  241.             char c;  242.             for (int i=start; i>=0; -i)  

135、 243.                   c = input.charAt(i);  244.                   if (c = 

136、9;.')   245.                         if (dotIndex != -1)  246.             &

137、#160;                 throw new IllegalArgumentException(  247.                       

138、;              "there have more than 1 dots in the number.");  248.                  

139、       else  249.                               dotIndex = i;  250.    

140、;                else if (!Character.isDigit(c)   251.                        &#

141、160;return i + 1;  252.                    else if (i = 0)   253.              &

142、#160;          return 0;  254.                     255.              &

143、#160;256.             throw new IllegalArgumentException("not a number.");  257.         258.         259.   &

144、#160;   /* 260.        * read the next number 261.        * param input 262.        * param start 263.    

145、;    * return 264.        * throws IllegalArgumentException 265.        */  266.       private static int readDouble(String i

146、nput, int start)  267.       throws IllegalArgumentException   268.             int len = input.length();  269.      

147、60;      int dotIndex = -1;  270.             char c;  271.             for (int i=start; i<

148、len; +i)   272.                   c = input.charAt(i);  273.                   i

149、f (c = '.')   274.                         if (dotIndex != -1)  275.         

150、                      throw new IllegalArgumentException(  276.                          

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论