×

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

Delete the Middle element of the Linked List in C

Delete the Middle element of the Linked List in C This article has given a singly linked list and will delete the middle element of the given linked list. Example:  The given...

3 minutes read.

Applications of trees in data structures

Data structures Storage used to organize and store data is known as the data structure. It is a method of managing computerized data to translate or retrieve it more efficiently. A...

7 minutes read.

Given a Binary Tree Print the Shortest Path

Implementation // Writing a program in C++ to find the shortest between the nodes i and j.  #include <bits/stdc++.h> using namespace std; // the given function will print the path between nodes i and...

7 minutes read.

Bitonical Sort

Arranging an unordered collecttion of things into asignificant order. •Comparision Based Model: Bubble Sort, Selection Sort -->Non-Comparison Based. Model: Bucket Sort or on the other hand a Count Sort Bitonic Sort: Bitonic sort Algorithm was made...

5 minutes read.

Convert Binary Tree into a Threaded Binary Tree

Implementation /*Writing a C++ program that will help us change the binary tree into a threaded binary tree and help us transform. */ #include <bits/stdc++.h> using namespace std; /*Creating the structure of a node...

11 minutes read.

Invert binary tree

Invert binary tree is a mirror image of a tree. It is pretty much the same compared to the only difference: its left and right children are swapped with the...

4 minutes read.

Sorting Algorithms in Data Structures

A sorting algorithm is used to organize the elements of an array or list. Sorting an array, for example. Unsorted array 572941 Sorted array 124579 We're sorting the array in ascending order right now. This procedure...

4 minutes read.

Insertion Sort vs Selection Sort

In this article, we will discuss insertion sort, Selection sort and the basic differences between these two sorting techniques in detail: What is Insertion Sort? Insertion Sort – The insertion sort is...

5 minutes read.

What is a full Binary Tree?

A full binary tree is considered to be a special kind of binary tree in which every single node or leaf node present either contains two children or no children...

4 minutes read.

Bookshop management system using file handling in C++

We see different software in every hospitals or library to manage their database. It is very important to store organization’s data. So we use this software. Now we are going...

5 minutes read.

Operations on 2D-Arrays

Two Dimensional Array Operations Adding Elements to Two-D Arrays We must put data in both rows and columns when inserting items in 2-D Arrays. As a result, we employ the idea of...

10 minutes read.

Extended Binary Tree

A form of binary tree known as an extended binary tree replaces all of the original tree's null subtrees with special nodes known as external nodes, while the remaining nodes...

4 minutes read.

Operations of B Tree in C++ Language

B tree tends to be a self-aligning and balancing tree that helps us organise our data and document safely. We know that every data or information in the B tree...

9 minutes read.

Reverse the Singly Linked List in C

Reverse the Singly Linked List in C This article has given a singly linked list and will reverse the linked list by changing the links between nodes. Example:                         Input:  2 -> 4...

3 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.

Delete N nodes after M nodes of a linked list

Delete N nodes after M nodes of a linked list In this problem, we have given a linked list and two integers M and N. We need to traverse the linked...

3 minutes read.

Dynamic memory allocation of structure in C

We can normally store elements of the same datatype with the help of an array in C programming. We can store multiple numbers of elements of a character data type...

5 minutes read.

Lowest Common Ancestor in a Binary Tree

The lowest node in the tree that contains both n1 and n2 as descendants is the lowest common ancestor (LCA), and n1 and n2 are the nodes for which we...

11 minutes read.

Insertion in B+ Tree

We will learn how to insert a node in the B+ tree and what are the different properties we are going to follow. Except for the root node, every node should...

5 minutes read.

Linked List Representation of Binary Tree

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. The word binary itself represents its meaning; we know that...

4 minutes read.