Infix to Postfix Conversion using Stack

Problem statement

Given an Infix arithmetic expression , convert it into an equivalent postfix expression .

Expression will be given in the form of string , where alphabetic characters i.e a-z or A-Z denotes operands and operators are ( + , – , * , / ) . Expression can also have brackets i.e β€˜(’ and β€˜)’.

Sample example :

Input infix expression : a * ( b + c + d)

Output postfix expression : abc+d+*

Input Infix expression : a*b

Output postfix expression : ab*

Introduction to Arithmetic Notations

Any arithmetic expression consists of operands and operators . The way we arrange our operators and operands to write the arithmetic expression is called Notation .

There are three different notations for writing the Arithmetic expression :

  • Infix expression An expression is said to be in infix notation if the operators in the expression are placed in between the operands on which the operator works.
    For example => a + b * c Infix expressions are easy to read ,write and understand by humans , but not by computer It’s costly , in terms of time and space , to process Infix expressions

  • Postfix expression (Reverse Polish Notation) An expression is said to be in postfix notation if the operators in the expression are placed after the operands on which the operator works. For example => abc*+ It’s most used to notation for evaluating arithmetic expression

  • Prefix expression (or Polish Notation ) An expression is said to be in prefix notation if the operators in the expression are placed before the operands on which the operator works. For example => +a*bc

Precedence order and Associativity of Operators

PrecedenceTypeOperatorsAssociativity
1Postfix() [] -> . ++ —Left to Right
2Unary+ – ! ~ ++ — (type)* & sizeofRight to Left
3Multiplicative* / %Left to Right
4Additive+ –Left to Right
5Shift<<, >>Left to Right
6Relational< <= > >=Left to Right
7Equality== !=Left to Right
8Bitwise AND&Left to Right
9Bitwise XOR^Left to Right
10Bitwise OR|Left to Right
11Logical AND&&Left to Right
12Logical OR||Left to Right
13Conditional?:Right to Left
14Assignment= += -+ *= /= %= >>= <<= &= ^= |=Right to Left
15Comma,Left to Right

In this article we are going to see how we can convert Infix expressions to postfix expressions . For the simplicity and understanding purpose , we will consider only β€˜+’ , β€˜-’ ,’/’ , β€˜*’ , β€˜(’ and β€˜)’ .

Approach

Conversion of Infix to postfix can be done using stack . The stack is used to reverse the order of operators. Stack stores the operator , because it can not be added to the postfix expression until both of its operands are added . Precedence of operator also matters while converting infix to postfix , which we will discuss in the algorithm .

Note: Parentheses are used to override the precedence of operators , and it can be nested parentheses which need to be evaluated from inner to outer .

Algorithm

  1. Scan all the symbols one by one from left to right in the given Infix Expression.

  2. If the reading symbol is operand, then immediately append it to the Postfix Expression .

  3. If the reading symbol is left parenthesis ‘( ‘, then Push it onto the Stack.

  4. If the reading symbol is right parenthesis ‘)’, then Pop all the contents of the stack until the respective left parenthesis is popped and append each popped symbol to Postfix Expression.

  5. If the reading symbol is operator (+ , – , * , /), then Push it onto the Stack. However, first pop the operators which are already on the stack that have higher or equal precedence than the current operator and append them to the postfix . If open parenthesis is there on top of the stack then push the operator into the stack.

  6. If the input is over, pop all the remaining symbols from the stack and append them to the postfix .

Infix to Postfix example using dry run

Implementation

#include <bits/stdc++.h>
using namespace std;

int precedence(char ch){
	switch(ch){
		case '-':
		case '+':
			return 1;
		case '*':
		case '/':
			return 2;
		default:
			return -1;
	}
}
bool isOperand(char ch){
	return (ch>='a' && ch<='z') || (ch>='A' && ch <='Z');
}

string infixToPostfix(string infix){
	int n=infix.size();
	stack<char> st;
	string postfix;
	for(int i=0;i<n;i++){
		if(isOperand(infix[i])){
			//step 2
			postfix.push_back(infix[i]);
		}
		else if(infix[i] == '('){
			//step 3
			st.push('(');
		}
		else if(infix[i] == ')'){
			//step 4
			while( st.top() != '(' ){
				postfix.push_back(st.top());
				st.pop();
			}
			st.pop();
			
		}
		else{
			//step 5
			while(!st.empty() && st.top() != '(' && precedence(st.top()) >= precedence(infix[i])){
				postfix.push_back(st.top());
				st.pop();
			}
			st.push(infix[i]);
		}
	}
	
	while(!st.empty()){
		postfix.push_back(st.top());
		st.pop();
	}
	return postfix;
}

int main() {
	// your code goes here
	string infix="a*(b+c+d)";
	string postfix=infixToPostfix(infix);
	cout<<"Infix expression : "<<infix<<endl; 
	cout<<"Postfix expression : "<<postfix<<endl;
	return 0;
}

This article tried to discuss Infix to postfix conversion using stack. Hope this blog helps you understand and solve the problem. To practice more problems you can check out MYCODE | Competitive Programming at PrepBytes.

Leave a Reply

Your email address will not be published. Required fields are marked *