Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 469|回复: 0

[算法学习]中缀表达式转换为前缀及后缀表达式并求值(java实现)

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-11-28 00:06:05 | 显示全部楼层 |阅读模式
    它们都是对表达式的记法,因此也被称为前缀记法、中缀记法和后缀记法。它们之间的区别在于运算符相对与操作数的位置不同:前缀表达式的运算符位于与其相关的操作数之前;中缀和后缀同理。
          

          
    举例:
          

          (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,因此不要将其用于除研究之外的其他场合。

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

            下面是程序运行结果(绿色为用户输入):
       
            
             == 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
             
            

            
          
          
          
          
            
      
          
          
          
         
       
       
         
         
          
          

            
          

            
          
         
       

      


    源码下载:http://file.javaxxz.com/2014/11/28/000604640.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2025-2-25 04:17 , Processed in 0.341543 second(s), 34 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表