中缀到前缀算法

时间:2018-03-14 17:46:43

标签: c++ prefix infix-notation

我需要将Infix表达式转换为Prefix表达式。我的算法适用于没有括号的表达式,但是当我添加括号时,此算法不再起作用。

问题是当堆栈中有两个运算符时,算法会尝试获取左右操作数,但可能会发生堆栈中只有一个操作数。例如(1+2):算法推送(堆栈中的+operator以及1堆栈中的operand,但我需要其他操作数(2)。我想当我尝试访问operand堆栈的顶部时(我的代码是空的),我的代码被破坏了

这是我的代码:

void transformerenprefixe(vector<string> tableau)
{
    stack<string> Operand;
    stack<string> Operator;

    string token;
    string operatorElm;
    string rightOperand;
    string leftOperand;


    for (size_t i = 0; i < tableau.size(); i++)
    {
        token = tableau.at(i);
        if (checkOperand(token))
        {
            Operand.push(token);
        }
        else if (token == "(" || Operator.empty() || precedence(token) > precedence(Operator.top()))
        {
            Operator.push(token);
        }
        else if(token == ")")
        {
            while (Operator.top() != "(")
            {
                operatorElm = Operator.top();
                Operator.pop();
                rightOperand = Operand.top();
                Operand.pop();
                leftOperand = Operand.top();
                Operand.pop();
                string operande = operatorElm + leftOperand + rightOperand;
                Operand.push(operande);
            }
            operatorElm = Operator.top();
            Operator.pop();
        }
        else if(precedence(token) <= precedence(Operator.top()))
        {
            while (!Operator.empty() && precedence(token) <= precedence(Operator.top()))
            {
                operatorElm = Operator.top();
                Operator.pop();
                rightOperand = Operand.top();
                Operand.pop();
                leftOperand = Operand.top();
                Operand.pop();
                string operande = operatorElm + leftOperand + rightOperand;
                Operand.push(operande);
            }
            Operator.push(token);
        }
    }

    while (!Operator.empty())
    {
        operatorElm = Operator.top();
        Operator.pop();
        rightOperand = Operand.top();
        Operand.pop();
        leftOperand = Operand.top();
        Operand.pop();
        string operande = operatorElm + leftOperand + rightOperand;
        Operand.push(operande);
    }

    cout << "The prefix expression is : " << Operand.top() << endl;
}

0 个答案:

没有答案