简体   繁体   中英

shunting-yard algorithm how to convert a 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.

infixt(string s) {

infixExpression = s;
string temp;
stack = new Stack();

for (int i = 0; i < infixExpression.length(); i++) {

    if (infixExpression[i] != ' ') {
        temp += s[i];
    } else {
        if (isOperator(temp[0])) {
            while(!stack->isEmpty() && stack->top().toString().c_str()[0] != '(' && isHigherPrecedence(stack->top().toString().c_str()[0], temp[0])) {
                StackItem item = stack->top();
                prefixExpression += item.toString() + " ";
                stack->pop();
            }
            StackItem *item = new StackItem(temp);
            stack->push(*item);
        } else if (isOperand(temp[0])) {
            prefixExpression += temp + " ";
        } else if (temp[0] == '(') {
            StackItem *item = new StackItem(temp);
            stack->push(*item);
        } else if (temp[0] == ')') {
            while (!stack->isEmpty() && stack->top().toString().c_str()[0] != '(') {
                StackItem item = stack->top();
                prefixExpression += item.toString() + " ";
                stack->pop();
            }
            stack->pop();
        }
        temp = "";
    }
}
while (!stack->isEmpty()) {
    StackItem item = stack->top();
    prefixExpression += item.toString() + " ";
    stack->pop();
}
prefixExpression += " ;";
}

For infix to prefix convertion:

1 --> Reverse the infix expression (Handle the parentheses order while reversing. Example: Say you want to reverse this expression --> "(a+b) c" if you reverse this without ordering parentheses it will give you this --> "c )b+a(" so you have to order the parentheses.)

2 --> Apply postfix notation to the reversed infix expression ( While applying Shunting-Yard Algorithm if precedence of top of the operator stack and precedence of present operator is equal don't pop the operator stack just push the present operator to the operator stack and continue.)

3 --> Reverse the expression again and it will give you the prefix notation of original infix expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM