×

Data Structure Infix to Postfix Conversion

Infix to Postfix Conversion

The infix expression is easy to read and write by humans. In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep some rules and they can’t differentiate between operators and parenthesis easily. The Prefix and Postfix expressions are quite understandable for the computers. For the infix to postfix conversion, we use stack data structure because

it works on Last in First out principle.

Algorithm: -

Step 1: Firstly, we push “(“ into the stack and also we add “)” to the end of the given input expression.

Step 2: Then we scan the input expression from left to right and we repeat step 3 to 6 for each element of the input expression until the stack is empty.

Step 3: If we encounter an operand then we just add it to output expression.

Step 4: If we encounter the left or opening parenthesis the we push it into the stack.

Step 5: If we encounter an operator, then:

a. We repeatedly check the precedence of incoming operator with the top of stack if the precedence of it is higher than the top of the stack then we simply add it into the stack else we pop the top of stack and add it into the output expression then again check the incoming operator precedence with the new of the top of stack.

b. If the precedence of both operators (incoming operator and the top of the stack) are same then use associativity rule.

Step 6: If we encounter the right or closing parenthesis, then:

a. We repeatedly pop the operator from the stack and add it to the output expression until the left parenthesis is encountered.

b. Then remove the left parenthesis from the stack.

Example: -

                The Input / Infix Expression:    A + ( ( B + C ) + ( D + E ) * F ) / G )

Infix ExpressionStackPostfix Expression
A(A
+( +A
(( + (A
(( + ( (A
B( + ( (A B
+( + ( ( +A B
C( + ( ( +A B C
)( + (A B C +
+( + ( +A B C+
(( + ( + (A B C +
D( + ( + (A B C + D
+( + ( + ( +A B C + D
E( + ( + ( +A B C + D E
)( + ( +A B C + D E +
*( + ( + *A B C + D E +
F( + ( + *A B C + D E + F
)( +A B C + D E + F * +
/( + /A B C + D E + F * +
G( + /A B C + D E + F * + G
)EMPTYA B C + D E + F * + G / +

The Output / Postfix Expression:     A B C + D E + F * + G / +

C- Program to covert infix expression to postfix expression:

 #include<stdio.h>
 #include<string.h>
 #include<math.h>
 #include<stdlib.h>
 #define BLANK ' '
 #define TAB '\t'
 #define MAX 50
 void push(long int element);
 long int pop();
 void infix_to_postfix();
 long int postfixEval();
 int precedence(char element);
 int isEmpty();
 int whiteSpace( char );
 char infix[ MAX ], postfix[ MAX ];
 long int stack[MAX];
 int top;
 int main()
 {
         long int value;
         top = -1;
         printf("Enter infix : ");
         gets( infix );
         infix_to_postfix();
         printf("Postfix : %s\n",postfix);
         value = postfixEval();
         printf("Value of expression : %ld\n",value);
         return 0;
 }/*End of main()*/
 void infix_to_postfix()
 {
         unsigned int i, p = 0;
         char next;
         char element;
         for(i = 0; i<strlen(infix); i++)
         {
                 element = infix[i];
                 if(!whiteSpace(element))
                 {
                         switch(element)
                         {
                         case '(':
                                 push(element);
                                 break;
                         case ')':
                                 while((next = pop()) != '(' )
                                         postfix[p++]  =  next;
                                 break;
                         case '+':
                         case '-':
                         case '*':
                         case '/':
                         case '%':
                         case '^':
                                 while( !isEmpty( ) &&  precedence(stack[top] ) >= precedence( element ) )
                                         postfix[p++] = pop();
                                 push( element );
                                 break;
                         default:  /* if an operand comes */
                              postfix[p++] = element;
                         }
                 }
         }
         while( !isEmpty( ) )
                 postfix[p++] = pop();
         postfix[p] = '\0'; /* End postfix with'\0' to make it a string  */
 }/*End of infix_to_postfix()*/
 /* This function returns the precedence of the operator */
 int precedence(char element)
 {
         switch(element)
         {
         case '(':
                 return 0;
         case '+':
         case '-':
                 return 1;
         case '*':
         case '/':
         case '%':
                 return 2;
         case '^':
                 return 3;
         default :
                 return 0;
         }
 }
 /* End of precedence() */
 void push(long int element)
 {
         if( top > MAX )
         {
                 printf("Stack overflow\n");
                 exit(1);
         }
         stack[ ++top ] = element;
 }
 /* End of push() */
 long int pop()
 {
         if( isEmpty() )
         {
                 printf(" Stack underflow\n ");
                 exit(1);
         }
         return (stack[ top-- ]);
 }
 /* End of pop() */
 int isEmpty()
 {
         if(top == -1)
                 return 1;
         else
                 return 0;
 }
 /* End of isEmpty() */
 int whiteSpace(char element)
 {
         if( element == BLANK || element == TAB )
                 return 1;
         else
                 return 0;
 }
 /* End of whiteSpace() */
 long int postfixEval()
 {
         long int a, b, temp, result;
         unsigned int i;
         for( i = 0; i<strlen(postfix); i++ )
         {
                 if( postfix[i] <= '9' && postfix[i] >= '0' )
                         push( postfix[i]-'0' );
                 else
                 {
                         a = pop();
                         b = pop();
                         switch( postfix[i] )
                         {
                         case '+':
                                 temp = b+a;
                      break;
                         case '-':
                                 temp = b-a;
                                 break;
                         case '*':
                                 temp = b*a;
                                 break;
                         case '/':
                                 temp = b/a;
                                 break;
                         case '%':
                                 temp = b%a;
                                 break;
                         case '^':
                                 temp = pow( b, a );
                         }
                         push( temp );
                 }
         }
         result = pop();
         return result;
 } 

Output: -

Time Complexity: -

The time complexity of infix to postfix operation is O(n^2) and the space complexity is O(n).


Related Topics

Sparse Matrix in Data Structure

Sparse Matrix The sparse matrix is a two-dimensional data object which is made by m rows and n columns, so we can say the number of data values in sparse matrix...

6 minutes read.

Recaman’s Sequence

Recamán's succession repeat connection in arithmetic and software engineering. Since its components are obviously connected with the past components, they are as often as possible characterized utilizing recursion. It takes its...

4 minutes read.

Serialize and Deserialize a Binary Tree

Implementation // Writing a C++ program to check the serialization and deserialization of binary tree.   #include <iosstream> /* A binary tree node contains a key and a pointer to the left and right...

4 minutes read.

Insertion Sort vs Bubble Sort

In this article, we will see the major differences between Insertion Sort and Bubble Sort. Before that, let’s have a quick overview of what these sorting algorithms are and what’s...

4 minutes read.

Red-black Tree in Data Structures?

A type of binary tree which is known as the Red-Black tree, is a specialized and unique tree. What is the urgency or, to be more precise, the necessity of...

10 minutes read.

Operations on Queue in Data Structures

A queue is a linear structure where operations are done in a specific sequence. Queues are abstract data structures that are comparable to Stacks. A queue, unlike a stack, is...

8 minutes read.

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Optimal binary search tree using dynamic programming

Implementation // We are creating a presentation where we will present a recursive method of the optimal binary search tree problem.  #include <bits/stdc++.h> using namespace std; //creating a utility function that will help us...

9 minutes read.

Stack vs Array

Difference between Array and Stack In this article, we are going to discuss the major differences between the stack and array data structures: Array – In the data structure, the array is...

3 minutes read.

Data Structures Algorithms

What is an Algorithm? An algorithm is a sequence of steps used to complete a job or get a desired result. It is similar to programming building elements that let cell...

4 minutes read.

Right side view of binary tree

The right view of the binary tree is generally known to be that side viewed from the right direction of the point of view. To be more precise, the right-side...

8 minutes read.

Introduction to 1D-Arrays

One Dimensional Array Technical Definitions The simplest version of an Array is a One-Dimensional Array, in which the items are stored linearly and may be accessed individually by supplying the index value...

6 minutes read.

What is B tree?

What do you mean by B Tree in Data Structures? In the technological world, a B tree is simply a well-managed and coordinated tree and an integral part of the data...

6 minutes read.

B Tree vs B + Tree: Data Structure

Difference Between B Tree and B+ Tree What is B Tree? B-Tree is a self-balancing or special type of m-way tree. B-Trees are used mainly in disc access. If we want...

3 minutes read.

Stack vs Queue: Data Structure

 Difference Between Stack and Queue What is Stack? The LIFO principle applies on insertion and deletion operations of the stack which means last inserted element to the stack will remove first....

3 minutes read.

Binary Tree to Doubly Linked List

Binary Tree to Doubly Linked List This article will explain how to convert the given binary tree into a Doubly Linked List. The left and right pointers in tree nodes are...

2 minutes read.

How to Start Learning DSA

All programmer experiences a point along the way where they wish they could approach a problem in a more effective manner. They finally learn about the terminology DSA while trying...

10 minutes read.

Semi-Structured data

In this article, we will discuss the semi-structured data. Data can be defined as the distinct piece of information that is gathered and translated for some purpose. It can be...

5 minutes read.

Merge Sort

Merge Sort is one of the most widely used sorting algorithms, and it is based on the Divide and Conquer principle. A problem is subdivided into multiple sub-problems in this method....

8 minutes read.

Stack Using Array

Stack – A Stack is a linear abstract data type used to store elements. It is also called last in first out or first in last out data structure because...

6 minutes read.