Search code examples
c++algorithmstackshunting-yard

shunting-yard algorithm infix into prefix implementation


I have successfully implemented the shunting-yard algorithm in C++ to convert an infix expression to a postfix expression (RPN). I need to modify my algorithm to return a prefix (polish) expression and I don't know how.

void Prefix::fromInfix()
{
//The stack contain the operators
std::stack<std::string> pile;
//This is the output
std::vector<std::string> sortie;
//The input is the std::vector<std::string> _expression

pile.push("(");
_expression.push_back(")");

for (auto iter = _expression.begin(); iter != _expression.end(); iter++)
{
    //statOperator detect if the token is an operator and the priority of the operator.
    short op = statOperator(*iter);
    if (*iter == "(")
        pile.push(*iter);
    else if (*iter == ")")
    {
        while (pile.top() != "(")
        {
            sortie.push_back(pile.top());
            pile.pop();
        }
        pile.pop();
    }
    else if (op)
    {
        while (!pile.empty())
        {
            short op2 = statOperator(pile.top());
            //if op2 is is have the priority and isn't a parenthesis.
            if (op <= op2 && op2 != 3)
            {
                sortie.push_back(pile.top());
                pile.pop();
            }
            else
                break;
        }
        pile.push(*iter);
    }
    else
        sortie.push_back(*iter);
}
_expression = sortie;
}

Solution

  • I just needed to read the input from right to left.

    for (auto iter = _expression.rbegin(); iter != _expression.rend(); iter++)
    

    Fully reverse the parenthesis role.

    _expression.insert(_expression.begin(), "(");
    pile.push(")");
    

    And in the loop.

    if (*iter == ")")
        pile.push(*iter);
    else if (*iter == "(")
    {
        while (pile.top() != ")")
        {
            sortie.push(pile.top());
            pile.pop();
        }
        pile.pop();
    }
    

    And reverse the output (I used a stack).

    while (!sortie.empty())
    {
        _expression.push_back(sortie.top());
        sortie.pop();
    }