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入门到精通教程
查看: 294|回复: 0

[算法学习]栈的应用实例:中缀表达式转为后缀表达式

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

    [LV.1]初来乍到

    发表于 2014-10-30 23:59:45 | 显示全部楼层 |阅读模式
    栈的应用实例
    一、中缀表达式转换为后缀表达式(只处理了+,-,*,/,(,))的代码:

       
    1. // infix.java
    2. // converts infix arithmetic expressions to postfix
    3. // to run this program: C>java InfixApp
    4. import java.io.*;            // for I/O
    5. ////////////////////////////////////////////////////////////////
    6. class StackX
    7.    {
    8.    private int maxSize;
    9.    private char[] stackArray;
    10.    private int top;
    11. //--------------------------------------------------------------
    12.    public StackX(int s)       // constructor
    13.       {
    14.       maxSize = s;
    15.       stackArray = new char[maxSize];
    16.       top = -1;
    17.       }
    18. //--------------------------------------------------------------
    19.    public void push(char j)  // put item on top of stack
    20.       { stackArray[++top] = j; }
    21. //--------------------------------------------------------------
    22.    public char pop()         // take item from top of stack
    23.       { return stackArray[top--]; }
    24. //--------------------------------------------------------------
    25.    public char peek()        // peek at top of stack
    26.       { return stackArray[top]; }
    27. //--------------------------------------------------------------
    28.    public boolean isEmpty()  // true if stack is empty
    29.       { return (top == -1); }
    30. //-------------------------------------------------------------
    31.    public int size()         // return size
    32.       { return top+1; }
    33. //--------------------------------------------------------------
    34.    public char peekN(int n)  // return item at index n
    35.       { return stackArray[n]; }
    36. //--------------------------------------------------------------
    37.    public void displayStack(String s)
    38.       {
    39.       System.out.print(s);
    40.       System.out.print("Stack (bottom-->top): ");
    41.       for(int j=0; j< size(); j++)
    42.          {
    43.          System.out.print( peekN(j) );
    44.          System.out.print(" ");
    45.          }
    46.       System.out.println("");
    47.       }
    48. //--------------------------------------------------------------
    49.    }  // end class StackX
    50. ////////////////////////////////////////////////////////////////
    51. class InToPost                  // infix to postfix conversion
    52.    {
    53.    private StackX theStack;
    54.    private String input;
    55.    private String output = "";
    56. //--------------------------------------------------------------
    57.    public InToPost(String in)   // constructor
    58.       {
    59.       input = in;
    60.       int stackSize = input.length();
    61.       theStack = new StackX(stackSize);
    62.       }
    63. //--------------------------------------------------------------
    64.    public String doTrans()      // do translation to postfix
    65.       {
    66.       for(int j=0; j< input.length(); j++)      // for each char
    67.          {
    68.          char ch = input.charAt(j);            // get it
    69.          theStack.displayStack("For "+ch+" "); // *diagnostic*
    70.          switch(ch)
    71.             {
    72.             case "+":               // it"s + or -
    73.             case "-":
    74.                gotOper(ch, 1);      // go pop operators
    75.                break;               //   (precedence 1)
    76.             case "*":               // it"s * or /
    77.             case "/":
    78.                gotOper(ch, 2);      // go pop operators
    79.                break;               //   (precedence 2)
    80.             case "(":               // it"s a left paren
    81.                theStack.push(ch);   // push it
    82.                break;
    83.             case ")":               // it"s a right paren
    84.                gotParen(ch);        // go pop operators
    85.                break;
    86.             default:                // must be an operand
    87.                output = output + ch; // write it to output
    88.                break;
    89.             }  // end switch
    90.          }  // end for
    91.       while( !theStack.isEmpty() )     // pop remaining opers
    92.          {
    93.          theStack.displayStack("While ");  // *diagnostic*
    94.          output = output + theStack.pop(); // write to output
    95.          }
    96.       theStack.displayStack("End   ");     // *diagnostic*
    97.       return output;                   // return postfix
    98.       }  // end doTrans()
    99. //--------------------------------------------------------------
    100.    public  void gotOper(char opThis, int prec1)
    101.       {                                // got operator from input
    102.       while( !theStack.isEmpty() )
    103.          {
    104.          char opTop = theStack.pop();
    105.          if( opTop == "(" )            // if it"s a "("
    106.             {
    107.             theStack.push(opTop);      // restore "("
    108.             break;
    109.             }
    110.          else                          // it"s an operator
    111.             {
    112.             int prec2;                 // precedence of new op
    113.             if(opTop=="+" || opTop=="-")  // find new op prec
    114.                prec2 = 1;
    115.             else
    116.                prec2 = 2;
    117.             if(prec2 < prec1)          // if prec of new op less
    118.                {                       //    than prec of old
    119.                theStack.push(opTop);   // save newly-popped op
    120.                break;
    121.                }
    122.             else                       // prec of new not less
    123.                output = output + opTop;  // than prec of old
    124.             }  // end else (it"s an operator)
    125.          }  // end while
    126.       theStack.push(opThis);           // push new operator
    127.       }  // end gotOp()
    128. //--------------------------------------------------------------
    129.    public  void gotParen(char ch)
    130.       {                             // got right paren from input
    131.       while( !theStack.isEmpty() )
    132.          {
    133.          char chx = theStack.pop();
    134.          if( chx == "(" )           // if popped "("
    135.             break;                  // we"re done
    136.          else                       // if popped operator
    137.             output = output + chx;  // output it
    138.          }  // end while
    139.       }  // end popOps()
    140. //--------------------------------------------------------------
    141.    }  // end class InToPost
    142. ////////////////////////////////////////////////////////////////
    143. class InfixApp
    144.    {
    145.    public static void main(String[] args) throws IOException
    146.       {
    147.       String input, output;
    148.       while(true)
    149.          {
    150.          System.out.print("Enter infix: ");
    151.          System.out.flush();
    152.          input = getString();         // read a string from kbd
    153.          if( input.equals("") )       // quit if [Enter]
    154.             break;
    155.                                       // make a translator
    156.          InToPost theTrans = new InToPost(input);
    157.          output = theTrans.doTrans(); // do the translation
    158.          System.out.println("Postfix is " + output + "
    159. ");
    160.          }  // end while
    161.       }  // end main()
    162. //--------------------------------------------------------------
    163.    public static String getString() throws IOException
    164.       {
    165.       InputStreamReader isr = new InputStreamReader(System.in);
    166.       BufferedReader br = new BufferedReader(isr);
    167.       String s = br.readLine();
    168.       return s;
    169.       }
    170. //--------------------------------------------------------------
    171.    }  // end class InfixApp
    172. ////////////////////////////////////////////////////////////////
    复制代码

       
      运行结果:
        C:xx>java InfixApp
    Enter infix: a+b*(c-d)
    For a Stack (bottom-->top):
    For + Stack (bottom-->top):
    For b Stack (bottom-->top): +
    For * Stack (bottom-->top): +
    For ( Stack (bottom-->top): + *
    For c Stack (bottom-->top): + * (
    For - Stack (bottom-->top): + * (
    For d Stack (bottom-->top): + * ( -
    For ) Stack (bottom-->top): + * ( -
    While Stack (bottom-->top): + *
    While Stack (bottom-->top): +
    End Stack (bottom-->top):
    Postfix is abcd-*+
       
      
       
       

         
       

         
       
      
      
      
       
      
      二、求后缀表达式的值(只处理了一位数)
    1. // postfix.java
    2. // parses postfix arithmetic expressions
    3. // to run this program: C>java PostfixApp
    4. import java.io.*;              // for I/O
    5. ////////////////////////////////////////////////////////////////
    6. class StackX
    7.    {
    8.    private int maxSize;
    9.    private int[] stackArray;
    10.    private int top;
    11. //--------------------------------------------------------------
    12.    public StackX(int size)      // constructor
    13.       {
    14.       maxSize = size;
    15.       stackArray = new int[maxSize];
    16.       top = -1;
    17.       }
    18. //--------------------------------------------------------------
    19.    public void push(int j)     // put item on top of stack
    20.       { stackArray[++top] = j; }
    21. //--------------------------------------------------------------
    22.    public int pop()            // take item from top of stack
    23.       { return stackArray[top--]; }
    24. //--------------------------------------------------------------
    25.    public int peek()           // peek at top of stack
    26.       { return stackArray[top]; }
    27. //--------------------------------------------------------------
    28.    public boolean isEmpty()    // true if stack is empty
    29.       { return (top == -1); }
    30. //--------------------------------------------------------------
    31.    public boolean isFull()     // true if stack is full
    32.       { return (top == maxSize-1); }
    33. //--------------------------------------------------------------
    34.    public int size()           // return size
    35.       { return top+1; }
    36. //--------------------------------------------------------------
    37.    public int peekN(int n)     // peek at index n
    38.       { return stackArray[n]; }
    39. //--------------------------------------------------------------
    40.    public void displayStack(String s)
    41.       {
    42.       System.out.print(s);
    43.       System.out.print("Stack (bottom-->top): ");
    44.       for(int j=0; j< size(); j++)
    45.          {
    46.          System.out.print( peekN(j) );
    47.          System.out.print(" ");
    48.          }
    49.       System.out.println("");
    50.       }
    51. //--------------------------------------------------------------
    52.    }  // end class StackX
    53. ////////////////////////////////////////////////////////////////
    54. class ParsePost
    55.    {
    56.    private StackX theStack;
    57.    private String input;
    58. //--------------------------------------------------------------
    59.    public ParsePost(String s)
    60.       { input = s; }
    61. //--------------------------------------------------------------
    62.    public int doParse()
    63.       {
    64.       theStack = new StackX(20);             // make new stack
    65.       char ch;
    66.       int j;
    67.       int num1, num2, interAns;
    68.       for(j=0; j< input.length(); j++)       // for each char,
    69.          {
    70.          ch = input.charAt(j);              // read from input
    71.          theStack.displayStack(""+ch+" ");  // *diagnostic*
    72.          if(ch >= "0" && ch <= "9")         // if it"s a number
    73.             theStack.push( (int)(ch-"0") ); //   push it
    74.          else                               // it"s an operator
    75.             {
    76.             num2 = theStack.pop();          // pop operands
    77.             num1 = theStack.pop();
    78.             switch(ch)                      // do arithmetic
    79.                {
    80.                case "+":
    81.                   interAns = num1 + num2;
    82.                   break;
    83.                case "-":
    84.                   interAns = num1 - num2;
    85.                   break;
    86.                case "*":
    87.                   interAns = num1 * num2;
    88.                   break;
    89.                case "/":
    90.                   interAns = num1 / num2;
    91.                   break;
    92.                default:
    93.                   interAns = 0;
    94.                }  // end switch
    95.             theStack.push(interAns);        // push result
    96.             }  // end else
    97.          }  // end for
    98.       interAns = theStack.pop();            // get answer
    99.       return interAns;
    100.       }  // end doParse()
    101.    }  // end class ParsePost
    102. ////////////////////////////////////////////////////////////////
    103. class PostfixApp
    104.    {
    105.    public static void main(String[] args) throws IOException
    106.       {
    107.       String input;
    108.       int output;
    109.       while(true)
    110.          {
    111.          System.out.print("Enter postfix: ");
    112.          System.out.flush();
    113.          input = getString();         // read a string from kbd
    114.          if( input.equals("") )       // quit if [Enter]
    115.             break;
    116.                                       // make a parser
    117.          ParsePost aParser = new ParsePost(input);
    118.          output = aParser.doParse();  // do the evaluation
    119.          System.out.println("Evaluates to " + output);
    120.          }  // end while
    121.       }  // end main()
    122. //--------------------------------------------------------------
    123.    public static String getString() throws IOException
    124.       {
    125.       InputStreamReader isr = new InputStreamReader(System.in);
    126.       BufferedReader br = new BufferedReader(isr);
    127.       String s = br.readLine();
    128.       return s;
    129.       }
    130. //--------------------------------------------------------------
    131.    }  // end class PostfixApp
    132. ////////////////////////////////////////////////////////////////
    133. 运行结果:
    134. C:cs>java   PostfixApp
    135. Enter postfix: 345+-
    136. 3 Stack (bottom-->top):
    137. 4 Stack (bottom-->top): 3
    138. 5 Stack (bottom-->top): 3 4
    139. + Stack (bottom-->top): 3 4 5
    140. - Stack (bottom-->top): 3 9
    141. Evaluates to -6
    复制代码
    注:3-(4+5)=-6
       
      

      










    源码下载:http://file.javaxxz.com/2014/10/30/235945687.zip
    回复

    使用道具 举报

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

    本版积分规则

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

    GMT+8, 2025-2-25 19:40 , Processed in 0.297725 second(s), 36 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

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