如何解决这个代码。 [中缀前缀。]

By simon at 2018-02-07 • 0人收藏 • 20人看过

码。完整脚本:https://code.sololearn.com/cntV26H7O83h/#java

     public String convert(String postfix){
      Stack s = new Stack(5);          
      for(int i = 0; i < postfix.length(); i++){
       char c = postfix.charAt(i);
       if(isOperator(c)){
        String b = s.pop();
        String a = s.pop();
        s.push(a+c+b);
       }
       else
        s.push(""+c);
      }

      return s.pop();
     }

     public static void main(String[] args) {
          Postin obj = new Postin();
          //InToPre obj2 = new InToPre();
          Scanner sc =new Scanner(System.in);
          System.out.print("Postfix : ");
          String postfix = sc.next();
          System.out.println("Infix : "+obj.convert(postfix));
          String reverseInput = reverse(postfix);
          System.out.println("Prefix : "+obj.reverse(postfix));

     } 
输入后缀:AB + 输出中缀:A + B 产量前缀:+ BA 为什么??我不明白。谢谢...

2 个回复 | 最后更新于 2018-02-07
2018-02-07   #1

继续。

                public static String reverse(String input) {
            int len = input.length();
            String reverse = "";
            char[] charr = new char[len];
            for (int i = 0; i < len; i++) {
            charr[i] = input.charAt(i);
            }
            for (int i = 0; i < len / 2; i++) {
            char temp = charr[i];
            charr[i] = charr[len - i - 1];
            charr[len - i - 1] = temp;
            }
            for (int j = 0; j < len; j++) {
            reverse += charr[j];
            }
            return reverse;
            }

2018-02-07   #2

Stack.java

public class Stack {
public static int N;
public static int TOP;
public static String[]S;

public Stack(int size) {
    N = size;
    TOP = -1;
    S = new String[N]; 
}
public void push(String x) {
    if(TOP == (N-1)) {
        System.out.println("FULL");
    }
    else{
        TOP = TOP+1;
        S[TOP] = x;
    }
}
public String pop() {
    String x = " ";
    if(TOP < 0) {
        System.out.println("Empty");
    }
    else {
        x = S[TOP];
        TOP = TOP-1;
    }
    return x;
}
public void printStack() {
    System.out.print("Num : [");
    for(int i=0; i<=TOP; i++)
        System.out.print(""+S[i]);
    System.out.println("]");
}
}

登录后方可回帖

Loading...