zoukankan      html  css  js  c++  java
  • 利用栈结构生成后缀表达式

    利用栈结构来构建后缀表达式

    关于后缀表达式,推荐博客http://blog.csdn.net/antineutrino/article/details/6763722/

    博客中详细介绍了表达式的生成过程。这里作简要介绍。

    后缀表达式的生成准则:


    利用该准则转换A*(B+C)


    利用该准则转换A+B*C


    利用该准则转换A+B-C



    有了这个准则,我们就可以设计一个栈来实现后缀表达式的转换。

    // infix.java
    // converts infix arithmetic expressions to postfix
    // to run this program: C>java InfixApp
    import java.io.*;            // for I/O
    ////////////////////////////////////////////////////////////////
    class StackX//定义栈结构
       {
       private int maxSize;
       private char[] stackArray;
       private int top;
    //--------------------------------------------------------------
       public StackX(int s)       // constructor
          {
          maxSize = s;
          stackArray = new char[maxSize];
          top = -1;
          }
    //--------------------------------------------------------------
       public void push(char j)  // put item on top of stack
          { stackArray[++top] = j; }
    //--------------------------------------------------------------
       public char pop()         // take item from top of stack
          { return stackArray[top--]; }
    //--------------------------------------------------------------
       public char peek()        // peek at top of stack
          { return stackArray[top]; }
    //--------------------------------------------------------------
       public boolean isEmpty()  // true if stack is empty
          { return (top == -1); }
    //-------------------------------------------------------------
       public int size()         // return size
          { return top+1; }
    //--------------------------------------------------------------
       public char peekN(int n)  // return item at index n
          { return stackArray[n]; }
    //--------------------------------------------------------------
       public void displayStack(String s)//显示栈内容
          {
          System.out.print(s);
          System.out.print("Stack (bottom-->top): ");
          for(int j=0; j<size(); j++)
             {
             System.out.print( peekN(j) );
             System.out.print(' ');
             }
          System.out.println("");
          }
    //--------------------------------------------------------------
       }  // end class StackX
    ////////////////////////////////////////////////////////////////
    class InToPost                  // 定义后缀表达式转换准则
       {
       private StackX theStack;
       private String input;
       private String output = "";
    //--------------------------------------------------------------
       public InToPost(String in)   // constructor
          {
          input = in;
          int stackSize = input.length();
          theStack = new StackX(stackSize);
          }
    //--------------------------------------------------------------
       public String doTrans()      // do translation to postfix
          {
          for(int j=0; j<input.length(); j++)      // for each char
             {
             char ch = input.charAt(j);  // 获得input对应的字符数组中下标为j的字符值
             theStack.displayStack("For "+ch+" "); // *diagnostic*
             switch(ch)
                {
                case '+':               // it's + or -
                case '-':
                   gotOper(ch, 1);      // 第二个参数“1”表示+和-的优先级为1
                   break;               //   (precedence 1)
                case '*':               // it's * or /
                case '/':
                   gotOper(ch, 2);      //第二个参数“2”表示*和/的优先级为2
                   break;               //   (precedence 2)
                case '(':               // it's a left paren
                   theStack.push(ch);   // push it
                   break;
                case ')':               // it's a right paren
                   gotParen(ch);        // go pop operators
                   break;
                default:                // must be an operand
                   output = output + ch; // 如果是数字而不是操作符,不入栈直接输出
                   break;
                }  // end switch
             }  // end for
          while( !theStack.isEmpty() )     // pop remaining opers
             {
             theStack.displayStack("While ");  // *diagnostic*
             output = output + theStack.pop(); // write to output
             }
          theStack.displayStack("End   ");     // *diagnostic*
          return output;                   // return postfix
          }  // end doTrans()
    //--------------------------------------------------------------
       public  void gotOper(char opThis, int prec1)//处理加减乘除操作符
          {                                // got operator from input
          while( !theStack.isEmpty() )
             {
             char opTop = theStack.pop();
             if( opTop == '(' )            // if it's a '('
                {
                theStack.push(opTop);      // restore '('
                break;
                }
             else                          // it's an operator
                {
                int prec2;                 // precedence of new op
    
                if(opTop=='+' || opTop=='-')  // find new op prec
                   prec2 = 1;
                else
                   prec2 = 2;
                if(prec2 < prec1)          // if prec of new op less
                   {                       //    than prec of old
                   theStack.push(opTop);   // save newly-popped op
                   break;
                   }
                else                       // prec of new not less
                   output = output + opTop;  // than prec of old
                }  // end else (it's an operator)
             }  // end while
          theStack.push(opThis);           // push new operator
          }  // end gotOp()
    //--------------------------------------------------------------
       public  void gotParen(char ch)//处理“)”
          {                             // got right paren from input
          while( !theStack.isEmpty() )
             {
             char chx = theStack.pop();
             if( chx == '(' )           // if popped '('
                break;                  // we're done
             else                       // if popped operator
                output = output + chx;  // output it
             }  // end while
          }  // end popOps()
    //--------------------------------------------------------------
       }  // end class InToPost
    ////////////////////////////////////////////////////////////////
    class InfixApp
       {
       public static void main(String[] args) throws IOException
          {
          String input, output;
          while(true)
             {
             System.out.print("Enter infix: ");
             System.out.flush();
             input = getString();         // read a string from kbd
             if( input.equals("") )       // quit if [Enter]
                break;
                                          // make a translator
             InToPost theTrans = new InToPost(input);
             output = theTrans.doTrans(); // do the translation
             System.out.println("Postfix is " + output + '
    ');
             }  // end while
          }  // end main()
    //--------------------------------------------------------------
       public static String getString() throws IOException
          {
          InputStreamReader isr = new InputStreamReader(System.in);
          BufferedReader br = new BufferedReader(isr);
          String s = br.readLine();
          return s;
          }
    //--------------------------------------------------------------
       }  // end class InfixApp
    ////////////////////////////////////////////////////////////////
    


  • 相关阅读:
    Owin
    C#不区分大小写的字符串替换(Replace)函数
    如何创建测试程序调试nginx数据结构
    一张脑图说清 Nginx 的主流程
    gdb常用命令记录
    nginx的configure流程
    c 编译器大全
    PHP 的 uniqid 函数产生的 id 真的是唯一的么?
    UUID那些事
    PHP 编码规范
  • 原文地址:https://www.cnblogs.com/kangsir/p/6653288.html
Copyright © 2011-2022 走看看