Pregunta

Here is my code:

    public String ShuntingYard(String input) {
    Tokenizer tokens = new Tokenizer(input);
    output = new LinkedList<String>();
    stack = new MyStack<String>(new LinkedList<String>(), new LinkedList<String>());

    while (tokens.hasNextToken()){
        String token = tokens.getNextToken();
        if (isOperator(token)){
            while (!stack.isEmpty() && isOperator(stack.peek())){
                    if ((leftassoc(token)&&precedence(token)<=precedence(stack.peek())) ||
                            (precedence(token)<precedence(stack.peek()))){
                        output.add(stack.pop());
                    }
                    else break; }
                    stack.push(token);

                }

                output.add(token); 
            }
        while (!stack.isEmpty())
            output.add(stack.pop());

        return output.toString();

        }

With an input 3 + 5 * 6 + 7, it's supposed to return 3 5 6 * + 7 +, but instead I get 3 + 5 * 6 + 7 + *. I'm confused as to why, since I followed the algorithm instructions on the Wikipedia page...am I messing up somewhere else? Thanks for the help in advance!

¿Fue útil?

Solución

Bascially you have a missing 'else'. Check the algorithm against your code. You're not handling the case correctly after the if (isOperator()) branch is or isn't taken. You also haven't implemented '(' or ')'. There may be other errors or omissions.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top