需要帮助使用堆栈将Postfix转换为Infix

时间:2019-03-27 05:24:54

标签: java stack postfix-notation

作为我的家庭作业,我编写了将后缀转换为全括号内的中缀的代码,但是此代码只能转换具有一位数字的中缀表达式。我需要转换2位数或更多位数的中缀表达式的帮助。

//Here's my code. My class doesn't use collection in JAVA.
//Classes and Interfaces for stack, list, and tree are provided.
private static final String DIGITS = "0123456789";

public static String convertPostfixtoInfix(String toPostfix)
{
    LinkedStack<String> s = new LinkedStack<>();

    for(int i=0; i<toPostfix.length(); i++)
    {
        if(DIGITS.indexOf(toPostfix.charAt(i)) != -1)
        {
            s.push(toPostfix.charAt(i)+"");
        }
        else if(toPostfix.charAt(i) == " ");{}//do nothing for blank.
        else
        {
            String temp = "";
            temp += toPostfix.charAt(i);

            String num1 = s.top();
            s.pop();
            String num2 = s.top();
            s.pop();
            s.push("(" + num2 + temp + num1 + ")");
        }
    }

    return s.top();//top() is same as peek() method.
}

例如,使用此代码,

  

输入:4 5-9 2 1 + / *

     

输出:((4-5)*(9 /(2 + 1)))

     

输入:40 5-9 20 1 + / *

     

输出:(9 *(2 /(0 + 1)))

1 个答案:

答案 0 :(得分:0)

这是您的操作方式。

首先,要注意一点。这行代码是多余的:

private static final String DIGITS = "0123456789";

如果要检查字符是否为数字,只需使用

Character.isDigit();

但是为了简单起见,我保留了这一行。

现在,返回您的代码。为了提供解析多个数字的功能,您要做的就是在遇到数字时,在输入String中循环,直到第一个非数字字符。

我对您的代码做了一些更改,以向您展示其应如何工作的基本概念:

private static final String DIGITS = "0123456789";

public static String convertPostfixtoInfix(String toPostfix)
{
    LinkedStack<String> s = new LinkedStack<>();
    StringBuilder digitBuffer = new StringBuilder();  

    /* I've changed the 'for' to 'while' loop, 
       because we have to increment i variable inside the loop, 
       which is considered as a bad practice if done inside 'for' loop
    */
    int i = 0;
    while(i < toPostfix.length()) 
    {
        if(DIGITS.indexOf(toPostfix.charAt(i)) != -1)
        {
            //when a digit is encountered, just loop through toPostfix while the first non-digit char is encountered ...
            while (DIGITS.indexOf(toPostfix.charAt(i)) != -1) {
                digitBuffer.append(toPostfix.charAt(i++)); //... and add it to the digitBuffer
            }
            s.push(digitBuffer.toString());
            digitBuffer.setLength(0); //erase the buffer
        }
        //this if-else can also be replace with only one "if (toPostfix.charAt(i) != ' ')"
        else if(toPostfix.charAt(i) == ' ');{}//do nothing for blank.
        else
        {
            String temp = "";
            temp += toPostfix.charAt(i);

            String num1 = s.top();
            s.pop();
            String num2 = s.top();
            s.pop();
            s.push("(" + num2 + temp + num1 + ")");
        }
        i++;
    }

    return s.top();//top() is same as peek() method.
}
  

输入:40 5-9 20 1 + / *
  输出:((40-5)*(9 /(20 + 1)))