简体   繁体   中英

C++ Converting Postfix to infix

So i'm programming a cmd-based calculator in C++. I finished it, but i was wondering, after converting the infix to postfix, i have a queue called the postfix queue containing the operators/operands in correct order. How do I convert a postfix expression back to infix?

If you don't mind producing some extra parentheses, it should be pretty easy. You basically "evaluate" the postfix data about like usual, except that when you get to an operator, instead of evaluating that operator and pushing the result on the stack, you print out an open-paren, the first operand, the operator, the second operand, and finally a close-paren.

If you didn't mind changing the order, it would also be pretty easy to avoid the extraneous parentheses. Walk the expression backwards, rearranging things from operator operand operand into operand operator operand . If you encounter an operator where you need an operand, you have a sub-expression to print out similarly. You need to enclose that sub-expression in parentheses if and only if its operator is of lower precedence than the operator you encountered previously.

For example, consider: ab + c * . Walking this backwards, we get * , then c , so we start by printing out c * . Then we need another operand, but we have a + , so we have a sub-expression. Since + is lower precedence than * , we need to enclose that sub-expression in parentheses, so we get c * (b + a) .

Conversely, if we had: ab * c + , we'd start similarly, producing c + , but then since * is higher precedence that + , we can/could print out the a * b (or b * a ) without parens.

Note that with - or / (or anything else that isn't commutative) you'd have to be a bit more careful about getting the order of operands correct. Even so, you're not going to get the original expression back, only an expression that should be logically equivalent to it.

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