我已经成功地在 C++ 中实现了分流场算法,将中缀表达式转换为后缀表达式 (RPN)。我需要修改我的算法以返回前缀(抛光)表达式,但我不知道如何。
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;
}