Convert Infix expression to Postfix expression
Last Updated :
26 Dec, 2023
Write a program to convert an Infix expression to Postfix form.
Infix expression: The expression of the form “a operator b” (a + b) i.e., when an operator is in-between every pair of operands.
Postfix expression: The expression of the form “a b operator” (ab+) i.e., When every pair of operands is followed by an operator.
Examples:
Input: A + B * C + D
Output: ABC*+D+
Input: ((A + B) – C * (D / E)) + F
Output: AB+CDE/*-F+ Â
Why postfix representation of the expression?Â
The compiler scans the expression either from left to right or from right to left.Â
Consider the expression: a + b * c + d
- The compiler first scans the expression to evaluate the expression b * c, then again scans the expression to add a to it.Â
- The result is then added to d after another scan.Â
The repeated scanning makes it very inefficient. Infix expressions are easily readable and solvable by humans whereas the computer cannot differentiate the operators and parenthesis easily so, it is better to convert the expression to postfix(or prefix) form before evaluation.
The corresponding expression in postfix form is abc*+d+. The postfix expressions can be evaluated easily using a stack.Â
How to convert an Infix expression to a Postfix expression?
To convert infix expression to postfix expression, use the stack data structure. Scan the infix expression from left to right. Whenever we get an operand, add it to the postfix expression and if we get an operator or parenthesis add it to the stack by maintaining their precedence.
Below are the steps to implement the above idea:
- Scan the infix expression from left to right.Â
- If the scanned character is an operand, put it in the postfix expression.Â
- Otherwise, do the following
- If the precedence and associativity of the scanned operator are greater than the precedence and associativity of the operator in the stack [or the stack is empty or the stack contains a ‘(‘ ], then push it in the stack. [‘^‘ operator is right associative and other operators like ‘+‘,’–‘,’*‘ and ‘/‘ are left-associative].
- Check especially for a condition when the operator at the top of the stack and the scanned operator both are ‘^‘. In this condition, the precedence of the scanned operator is higher due to its right associativity. So it will be pushed into the operator stack.Â
- In all the other cases when the top of the operator stack is the same as the scanned operator, then pop the operator from the stack because of left associativity due to which the scanned operator has less precedence.Â
- Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator.
- After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.)Â
- If the scanned character is a ‘(‘, push it to the stack.Â
- If the scanned character is a ‘)’, pop the stack and output it until a ‘(‘ is encountered, and discard both the parenthesis.Â
- Repeat steps 2-5 until the infix expression is scanned.Â
- Once the scanning is over, Pop the stack and add the operators in the postfix expression until it is not empty.
- Finally, print the postfix expression.
Illustration:
Follow the below illustration for a better understanding
Consider the infix expression exp = “a+b*c+d”
and the infix expression is scanned using the iterator i, which is initialized as i = 0.
1st Step: Here i = 0 and exp[i] = ‘a’ i.e., an operand. So add this in the postfix expression. Therefore, postfix = “a”.
Add ‘a’ in the postfix
2nd Step: Here i = 1 and exp[i] = ‘+’ i.e., an operator. Push this into the stack. postfix = “a” and stack = {+}.
Push ‘+’ in the stack
3rd Step: Now i = 2 and exp[i] = ‘b’ i.e., an operand. So add this in the postfix expression. postfix = “ab” and stack = {+}.
Add ‘b’ in the postfix
4th Step: Now i = 3 and exp[i] = ‘*’ i.e., an operator. Push this into the stack. postfix = “ab” and stack = {+, *}.
Push ‘*’ in the stack
5th Step: Now i = 4 and exp[i] = ‘c’ i.e., an operand. Add this in the postfix expression. postfix = “abc” and stack = {+, *}.
Add ‘c’ in the postfix
6th Step: Now i = 5 and exp[i] = ‘+’ i.e., an operator. The topmost element of the stack has higher precedence. So pop until the stack becomes empty or the top element has less precedence. ‘*’ is popped and added in postfix. So postfix = “abc*” and stack = {+}.Â
Pop ‘*’ and add in postfix
Now top element is ‘+‘ that also doesn’t have less precedence. Pop it. postfix = “abc*+”.Â
Pop ‘+’ and add it in postfix
Now stack is empty. So push ‘+’ in the stack. stack = {+}.
Push ‘+’ in the stack
7th Step: Now i = 6 and exp[i] = ‘d’ i.e., an operand. Add this in the postfix expression. postfix = “abc*+d”.
Add ‘d’ in the postfix
Final Step: Now no element is left. So empty the stack and add it in the postfix expression. postfix = “abc*+d+”.
Pop ‘+’ and add it in postfix
Below is the implementation of the above algorithm:Â
C++14
#include <bits/stdc++.h>
using namespace std;
int prec( char c) {
if (c == '^' )
return 3;
else if (c == '/' || c == '*' )
return 2;
else if (c == '+' || c == '-' )
return 1;
else
return -1;
}
char associativity( char c) {
if (c == '^' )
return 'R' ;
return 'L' ;
}
void infixToPostfix(string s) {
stack< char > st;
string result;
for ( int i = 0; i < s.length(); i++) {
char c = s[i];
if ((c >= 'a' && c <= 'z' ) || (c >= 'A' && c <= 'Z' ) || (c >= '0' && c <= '9' ))
result += c;
else if (c == '(' )
st.push( '(' );
else if (c == ')' ) {
while (st.top() != '(' ) {
result += st.top();
st.pop();
}
st.pop();
}
else {
while (!st.empty() && prec(s[i]) < prec(st.top()) ||
!st.empty() && prec(s[i]) == prec(st.top()) &&
associativity(s[i]) == 'L' ) {
result += st.top();
st.pop();
}
st.push(c);
}
}
while (!st.empty()) {
result += st.top();
st.pop();
}
cout << result << endl;
}
int main() {
string exp = "a+b*(c^d-e)^(f+g*h)-i" ;
infixToPostfix( exp );
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int prec( char c) {
if (c == '^' )
return 3;
else if (c == '/' || c == '*' )
return 2;
else if (c == '+' || c == '-' )
return 1;
else
return -1;
}
char associativity( char c) {
if (c == '^' )
return 'R' ;
return 'L' ;
}
void infixToPostfix( char s[]) {
char result[1000];
int resultIndex = 0;
int len = strlen (s);
char stack[1000];
int stackIndex = -1;
for ( int i = 0; i < len; i++) {
char c = s[i];
if ((c >= 'a' && c <= 'z' ) || (c >= 'A' && c <= 'Z' ) || (c >= '0' && c <= '9' )) {
result[resultIndex++] = c;
}
else if (c == '(' ) {
stack[++stackIndex] = c;
}
else if (c == ')' ) {
while (stackIndex >= 0 && stack[stackIndex] != '(' ) {
result[resultIndex++] = stack[stackIndex--];
}
stackIndex--;
}
else {
while (stackIndex >= 0 && (prec(s[i]) < prec(stack[stackIndex]) ||
prec(s[i]) == prec(stack[stackIndex]) &&
associativity(s[i]) == 'L' )) {
result[resultIndex++] = stack[stackIndex--];
}
stack[++stackIndex] = c;
}
}
while (stackIndex >= 0) {
result[resultIndex++] = stack[stackIndex--];
}
result[resultIndex] = '\0' ;
printf ( "%s\n" , result);
}
int main() {
char exp [] = "a+b*(c^d-e)^(f+g*h)-i" ;
infixToPostfix( exp );
return 0;
}
|
Java
import java.util.Stack;
public class InfixToPostfix {
static int prec( char c) {
if (c == '^' )
return 3 ;
else if (c == '/' || c == '*' )
return 2 ;
else if (c == '+' || c == '-' )
return 1 ;
else
return - 1 ;
}
static char associativity( char c) {
if (c == '^' )
return 'R' ;
return 'L' ;
}
static void infixToPostfix(String s) {
StringBuilder result = new StringBuilder();
Stack<Character> stack = new Stack<>();
for ( int i = 0 ; i < s.length(); i++) {
char c = s.charAt(i);
if ((c >= 'a' && c <= 'z' ) || (c >= 'A' && c <= 'Z' ) || (c >= '0' && c <= '9' )) {
result.append(c);
}
else if (c == '(' ) {
stack.push(c);
}
else if (c == ')' ) {
while (!stack.isEmpty() && stack.peek() != '(' ) {
result.append(stack.pop());
}
stack.pop();
}
else {
while (!stack.isEmpty() && (prec(s.charAt(i)) < prec(stack.peek()) ||
prec(s.charAt(i)) == prec(stack.peek()) &&
associativity(s.charAt(i)) == 'L' )) {
result.append(stack.pop());
}
stack.push(c);
}
}
while (!stack.isEmpty()) {
result.append(stack.pop());
}
System.out.println(result);
}
public static void main(String[] args) {
String exp = "a+b*(c^d-e)^(f+g*h)-i" ;
infixToPostfix(exp);
}
}
|
Python3
def prec(c):
if c = = '^' :
return 3
elif c = = '/' or c = = '*' :
return 2
elif c = = '+' or c = = '-' :
return 1
else :
return - 1
def associativity(c):
if c = = '^' :
return 'R'
return 'L'
def infix_to_postfix(s):
result = []
stack = []
for i in range ( len (s)):
c = s[i]
if ( 'a' < = c < = 'z' ) or ( 'A' < = c < = 'Z' ) or ( '0' < = c < = '9' ):
result.append(c)
elif c = = '(' :
stack.append(c)
elif c = = ')' :
while stack and stack[ - 1 ] ! = '(' :
result.append(stack.pop())
stack.pop()
else :
while stack and (prec(s[i]) < prec(stack[ - 1 ]) or
(prec(s[i]) = = prec(stack[ - 1 ]) and associativity(s[i]) = = 'L' )):
result.append(stack.pop())
stack.append(c)
while stack:
result.append(stack.pop())
print (''.join(result))
exp = "a+b*(c^d-e)^(f+g*h)-i"
infix_to_postfix(exp)
|
C#
using System;
using System.Collections.Generic;
class Program
{
static int Prec( char c)
{
if (c == '^' )
return 3;
else if (c == '/' || c == '*' )
return 2;
else if (c == '+' || c == '-' )
return 1;
else
return -1;
}
static char Associativity( char c)
{
if (c == '^' )
return 'R' ;
return 'L' ;
}
static void InfixToPostfix( string s)
{
Stack< char > stack = new Stack< char >();
List< char > result = new List< char >();
for ( int i = 0; i < s.Length; i++)
{
char c = s[i];
if ((c >= 'a' && c <= 'z' ) || (c >= 'A' && c <= 'Z' ) || (c >= '0' && c <= '9' ))
{
result.Add(c);
}
else if (c == '(' )
{
stack.Push(c);
}
else if (c == ')' )
{
while (stack.Count > 0 && stack.Peek() != '(' )
{
result.Add(stack.Pop());
}
stack.Pop();
}
else
{
while (stack.Count > 0 && (Prec(s[i]) < Prec(stack.Peek()) ||
Prec(s[i]) == Prec(stack.Peek()) &&
Associativity(s[i]) == 'L' ))
{
result.Add(stack.Pop());
}
stack.Push(c);
}
}
while (stack.Count > 0)
{
result.Add(stack.Pop());
}
Console.WriteLine( string .Join( "" , result));
}
static void Main()
{
string exp = "a+b*(c^d-e)^(f+g*h)-i" ;
InfixToPostfix(exp);
}
}
|
Javascript
function prec(c) {
if (c == '^' )
return 3;
else if (c == '/' || c== '*' )
return 2;
else if (c == '+' || c == '-' )
return 1;
else
return -1;
}
function infixToPostfix(s) {
let st = [];
let result = "" ;
for (let i = 0; i < s.length; i++) {
let c = s[i];
if ((c >= 'a' && c <= 'z' ) || (c >= 'A' && c <= 'Z' ) || (c >= '0' && c <= '9' ))
result += c;
else if (c == '(' )
st.push( '(' );
else if (c == ')' ) {
while (st[st.length - 1] != '(' )
{
result += st[st.length - 1];
st.pop();
}
st.pop();
}
else {
while (st.length != 0 && prec(s[i]) <= prec(st[st.length - 1])) {
result += st[st.length - 1];
st.pop();
}
st.push(c);
}
}
while (st.length != 0) {
result += st[st.length - 1];
st.pop();
}
document.write(result + "</br>" );
}
let exp = "a+b*(c^d-e)^(f+g*h)-i" ;
infixToPostfix(exp);
|
Time Complexity: O(N), where N is the size of the infix expression
Auxiliary Space: O(N), where N is the size of the infix expression
Â
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...