예제 #1
0
  static String postfix(String infix) throws Exception {
    int error = 0;
    int len = infix.length();
    Stack<Character> sns = new Stack<Character>();
    StringBuilder postfix = new StringBuilder();
    int a = 0;
    int b = -1;
    int parleft = 0;
    int parright = 0;
    for (int i = 0; i < len; i++) {
      char ch = infix.charAt(i);
      if (ch == '(') parleft += 1;
      if (ch == ')') parright += 1;
      // unary를 ~로 바꿔줌
      if (ch == '-') {
        if (i == 0) ch = '~';
        else {
          char t = infix.charAt(i - 1);
          if (t == '+' || t == '-' || t == '*' || t == '/' || t == '%' || t == '(') ch = '~';
        }
      }
      // postfix로 변환
      if ('0' <= ch && ch <= '9') {
        if (a == 1) postfix.append(ch);
        else {
          postfix.append(" ");
          postfix.append(ch);
        }
        a = 1;
        b++;
      } else if (ch == '+' || ch == '-' || ch == '(' || ch == '*' || ch == '^' || ch == '/'
          || ch == '%' || ch == '~') {
        if (ch == '(') {
          if (a == 1) throw new Exception();
          b = -1;
        }
        if (a == 0 && ch != '~' && ch != '(') error = 1;
        if (sns.isEmpty()) {
          sns.push(ch);
        } else {
          if (ch == '(' || ch == '~' || ch == '^') sns.push(ch);
          if (ch != '(' && ch != ')' && ch != '^' && ch != '~') {
            while (sns.isEmpty() == false
                && Priority.priority(sns.peek()) >= Priority.priority(ch)) {
              postfix.append(" ");
              postfix.append(sns.pop());
            }
            sns.push(ch);
          }
        }
        a = 0;
        b++;
      } else if (ch == ')') {
        if (b == 0) error = 1;
        while (sns.peek() != '(') {
          postfix.append(" ");
          postfix.append(sns.pop());
          if (sns.isEmpty()) error = 1;
        }
        sns.pop();
      }
      // 다른 연산자 때 ERROR 출력
      else {
        error = 1;
        break;
      }
    }
    while (sns.isEmpty() == false) {
      char f**k = sns.pop();
      if (f**k == '(') continue;
      postfix.append(" ");
      postfix.append(f**k);
    }
    if (parleft != parright) error = 1;
    if (error == 1) throw new Exception();

    return postfix.toString();
  }