DEV Community

Cover image for Infix to postfix conversion using stack in C++
Lalit Kumar
Lalit Kumar

Posted on

Infix to postfix conversion using stack in C++

This article discusses the method of converting infix to postfix using stack data structure.

Infix: infix is an expression in which the operator used to appear in the middle of operands in the expression. It looks something like this [operand operator operand]. For example → (A+B)*(C-D)

Postfix: postfix is also an expression but the difference is that the operator in this expression is present after two operands, something like [B D +].

Approach

First of all search for the infix in the expression from left to right. Initialize a vacant stack. Check if the scanned character is an operand then add it to the postfix string. And if the scanned character is an operator and the stack is empty push the character to the stack. If the stack is not empty then compare the precedence of the character with the element on top of stack.
When top Stack has higher precedence over the scanned character pop the stack else push the scanned character to stack. Repeat this procedure till the stack is not empty and top Stack has precedence over the character. Then repeat the process till all characters are scanned. When all characters are scanned, add any character that stack may have to the postfix string. When stack is not empty add top Stack to Postfix string and Pop the stack.Repeat the process as long as stack is not vacant.

For example check out this example :

https://www.kodlogs.com/blog/2240/infix-to-postfix-conversion-using-stack-in-c

Top comments (0)