使用堆栈的中缀到Postfix [英] Infix to Postfix using stacks

查看:102
本文介绍了使用堆栈的中缀到Postfix的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我是否正确行事。我正在尝试将中缀等式转换为后缀等式,如:

I'm not sure if I'm doing this right or not. I'm trying to convert infix equation to postfix equation like:

(3 + 4) * 2 

4 3 + 2 *

如果可能的话,我试图用一种方法完成所有这些。

I'm trying to do this all in one method if possible.

现在我收到了一个arrayoutofbounds错误,所以我在错误的地方或其他地方弹出。

Right now I'm getting an arrayoutofbounds error so the I'm popping in the wrong place or something.

这是infixtopostfix方法。

Here's the infixtopostfix method.

public void InfixToPostfix(String f) {
    Stacked postfix = new Stacked(100);
    Stacked op = new Stacked(100);
    char c;
    String fix = f;
    //String out = "";
    int out = 0;

    for (int i = 0; i < fix.length(); i++) {
        c = fix.charAt(i);

        if (c != '+' || c != '*' || c != '-' || c != '/' || c != '(' || c != ')') {
            // out += c;
            postfix.push(c);
        } 
        else if (c == '+' || c == '*' || c == '-' || c == '/') {
            if (c != ')') {
                op.push(c);
            } else {
                out = (char) op.pop();
                s.push(out);
            }
            out = (char) op.pop();
            System.out.println("THE POSTFIX = " + out)
        }
    }
}


推荐答案

  public class Postfix {

   private int priority(char ch) {
    if (ch == '^')
     return 3;
    if (ch == '/' || ch == '*')
     return 2;
    if (ch == '+' || ch == '-')
     return 1;
    return 0;
   }

   public String toPostfix(String in ) {

    String copy = in +")";
    Stack s = new Stack(copy.length());
    s.push('(');

    int i, l = copy.length();
    char ch;

    String r = "";
    for (i = 0; i < l; i++) {

     ch = copy.charAt(i);
     if (Character.isLetter(ch) == true)
      r += ch;

     else if (ch == '(')
      s.push(ch);

     else if (ch == ')') {
      while (s.seeTop() != '(')
       r += s.popSeeTop();

      s.pop();

     } else {
      while (priority(ch) <= priority(s.seeTop()))
       r += s.popSeeTop();

      s.push(ch);
     }
    }
    return r;
   }
  }

这篇关于使用堆栈的中缀到Postfix的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆