开发者

Preserving Parenthesis in Shunting Yard

I'm working on what is essentially the shunting yard algorithm, but moving infix to prefix instead of RPN I am trying to preserve parenthesis, and I'm having a devil of a time of it. Currenntly my code is

        String s = inFixList.get(i);
        Stack<Character> opStack = new Stack<Character>();
        Stack<Character> solutionStack = new Stack<Character>();
       开发者_高级运维 String solution = "";

        for(char c : s.toCharArray())
        {
            if(Character.isLetter(c)||Character.isDigit(c))
            {
                solutionStack.push(c);
            }
            else if(c == '(')
            {
                opStack.push(c);
                solutionStack.push(')');
            }
            else if(c == ')')
            {                   
                while(opStack.peek() != '(')
                {
                    solutionStack.push(opStack.pop());
                    solutionStack.push('(');
                }
                opStack.pop();
            }
            else if (!Character.isSpaceChar(c))
            {
                if(opStack.isEmpty())
                {
                    opStack.push(c);
                }                       
                else if(opStack.peek()!='(' &&(OPERATORS.indexOf(c) < OPERATORS.indexOf(opStack.peek())))
                {
                    opStack.push(c);
                }
                else if(!opStack.isEmpty()&&(opStack.peek()!='('))
                {
                    solutionStack.push(opStack.pop());
                    solutionStack.push('(');
                    opStack.push(c);

                }
                else
                {
                    opStack.push(c);
                }

            }
        }
        while(opStack.size() != 0)
        {
            solutionStack.push(opStack.pop());
            solutionStack.push('(');
        }
        while(!solutionStack.isEmpty())
        {
            solution+=solutionStack.pop();
        }

        System.out.println("Final Answer!"+solution);

This outputs the opening parenthesis correctly, but only one kind of closing parenthesis. Does anybody have any idea where I should be adding them? I swear I'm missing that last logical step to get where it goes...


I'm not sure if this is the problem, but I noticed in your code that you wrote

else if(c == '(')
{
   opStack.push(c);
   solutionStack.push(')');
}

Do you really want to push a close parenthesis here? Pushing an open parenthesis seems a lot more reasonable, though I could be wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜