×

Data structure: Infix to Prefix Conversion

Infix to Prefix Conversion

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. The Prefix and Postfix expression are quite understandable for the computers.

Algorithm

  • Firstly, we reverse input expression.
  • Then we scan input expression from left to right and repeat the steps which are   given below for every element of input expression until the stack is Empty.
  • If we encounter an operand then we add it in to the output expression.
  • If we encounter the right parenthesis then we push it into the stack.
  • If we encounter an operator then:
  • 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 top of stack.
  • If precedence of incoming operator and top of the stack are same then check associativity rule.
  • If we encounter left parenthesis then:
  • We repeatedly pop the operators from the stack and add to the output expression until a right parenthesis is encountered.
  • Remove the left parenthesis.
  • Exit

Example

                         Input Expression:        ( O ^ P ) * W / U / V * T + Q

                         Reversed I/P Expression:   Q + T * V / U / W * ) P ^ O (

Reversed I/P ExpressionStackOutput Expression
QEmptyQ
++Q
T+Q T
*+ *Q T
V+ *Q T V
/+ * /Q T V
U+ * /Q T V U
/+ * / /Q T V U
W+ * / /Q T V U W
*+ * / / *Q T V U W
)+ * / / * )Q T V U W
P+ * / / * )Q T V U W P
^+ * / / * ) ^Q T V U W P
O+ * / / * ) ^Q T V U W P O
(+ * / / * )Q T V U W P O ^
 + * / / *Q T V U W P O ^
 EMPTYQ T V U W P O ^ * / / * +

Reversed the O/P Expression:     + *  / / * ^ O P W U V T Q

C- Program to covert infix expression to prefix expression:

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


Related Topics

Inorder Successor in Binary Trees

The next node in the Inorder traversal of a binary tree is known as Inorder successor of that particular node. In a Binary Search Tree, the definition of Inorder successor can...

9 minutes read.

Delete a Node without head pointer from the linked list

Delete a Node without head pointer from the linked list This article will explain how to delete a node without a head pointer from the linked list. We have given a...

2 minutes read.

Graph Data Structure

A graph is a non-primitive and non-linear data structure. It is a group of (V, E) where V is a set of vertexes, and E is a set of edge....

3 minutes read.

String Operations in Data Structures

Operations on Strings Reversing the order of words in a sentence Reversing a string is a technique that reverses or alters the order of a given string so that the last character...

9 minutes read.

Adding one to the number represented an array of digits

You have given one array, which consists of values which represent the different digits of a number. You have to add 1 to this number and store the result in...

3 minutes read.

Strictly binary tree in Data Structures?

What is a strictly Binary Tree in Data Structures? There are various kinds of binary trees that we know exist in data structures, and they all have their purposes. In this...

4 minutes read.

Splay Tree

Splay Tree A splay tree is a self-balanced or self-adjusted binary search tree. We can say, Splay Tree is used in some cases where some elements or data are accessed more...

8 minutes read.

Given Two Binary Trees, Check if it is Symmetric

Implementation // creating a C++ program that will help us check whether the two given trees are mirror images of each other.  #include<bits/stdc++.h> using namespace std; /* A given binary tree has a data...

5 minutes read.

All About Minimum Cost Spanning Trees in Data Structure

Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system that stores, manages, and optimizes...

7 minutes read.

Permutation Sort or Bogo Sort

In Permutation Sort or Bogo Sort, you have been given one array, which consists of different values. You have to sort the array using BOGO sort. Let’s take an example: Input-...

3 minutes read.

Asymptotic Notation

Asymptotic notation is expressions that are used to represent the complexity of algorithms. The complexity of the algorithm is analyzed from two perspectives:  Time complexitySpace complexity Time complexity The time complexity of an algorithm is the...

3 minutes read.

Stack Using Linked List

In the linked list implementation of the stack, we use a linked list as the primitive data structure to create the stack. It is called the dynamic implementation of the...

6 minutes read.

Linear vs Non-Linear: Data Structure

What is Linear Data Structure? The data structure is said to be linear if the data elements are arranged linearly or we can say sequentially. In the linear data structure, the...

3 minutes read.

Quick Sort vs Merge Sort

In this article, we will take an overview of Quick Sort and Merge Sort and then discuss the differences between them. What is Quick Sort? Quick Sort – The idea behind the...

7 minutes read.

Linear vs Circular Queue: Data Structure

Difference Between Linear and Circular Queue What is Linear Queue? A linear queue is linear data structure which works on first in first out principle. We can say a linear queue is...

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

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.

Detect Loop in Linked List: Data Structure

Detect the Loop in Linked List: In this problem, we will be seeing some technique through which we can detect the loop in linked list. We will discuss each technique...

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

Linear vs Binary Search: Data Structure

Difference Between Linear and Binary Search What is Linear Search? A linear search also referred as a sequential search. It is a way to find an element within a list and it...

3 minutes read.