我已经在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;
}
答案 0 :(得分:1)
我只需要从右到左阅读输入。
for (auto iter = _expression.rbegin(); iter != _expression.rend(); iter++)
完全颠倒括号角色。
_expression.insert(_expression.begin(), "(");
pile.push(")");
在循环中。
if (*iter == ")")
pile.push(*iter);
else if (*iter == "(")
{
while (pile.top() != ")")
{
sortie.push(pile.top());
pile.pop();
}
pile.pop();
}
反转输出(我使用了堆栈)。
while (!sortie.empty())
{
_expression.push_back(sortie.top());
sortie.pop();
}