在Java中使用堆栈和队列将Infix转换为Postfix的问题

时间:2019-03-20 04:17:49

标签: java postfix-notation infix-notation

如果方程式包含NUM + /-/ * // NUM的任何变体,则它起作用。 但是,添加更多运算符将导致其无法使用,并且括号将导致无限循环。我希望有人能告诉我我哪里出了问题。我为长度代码表示歉意,任何帮助将不胜感激。

/*
Converts String equation in an Infix form into a Postfix format.
postFix is a stack object that currently uses the default constructor of DSAStack
hence there is an upper limit to how many characters can be entered. 
Likewise for infix.
opStack contains the operators for as long as it is needed.

eqArray contains the entered equation in an Array. The original line will be split on " ", aka a space between "characters".

order ensures that precedence of operators are kept.
*/   
    private static DSAQueue parseInfix(String equation)
    {
        DSAQueue postfix = new DSAQueue();
        DSAStack opStack = new DSAStack();
        DSAQueue infix = new DSAQueue();

        String term = "1";
        String[] eqArray = readType.splitLine(equation, " ");

        for(int i = 0; i < eqArray.length; i++)
        {
            infix.enqueue(eqArray[i]);
        }       
        while(!infix.isEmpty())
        {
            term = null;
            term = (String) infix.dequeue();

            if(term.equals("("))
            {
                opStack.push("(");
            }
            else if(term.equals(")"))
            {
                while(!(opStack.peek().equals("(")))
                {
                    postfix.enqueue(opStack.pop());
                }
                opStack.pop();  
            }
            else if(term.equals("+") || term.equals("-") || term.equals("*") || term.equals("/")
            {
                while((!opStack.isEmpty())&&((opStack.peek()).equals("(")))
                { 
                    if(order(opStack.peek()) > order(term))
                    {
                        postfix.enqueue(opStack.pop());
                    }
                }
                opStack.push(term);
            }
            else
            {
                postfix.enqueue(term);
            }
        }

        while(!opStack.isEmpty())
        {
            postfix.enqueue(opStack.pop());
        }        

        return postfix;
    }

0 个答案:

没有答案