×

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

Print kth least significant bit number

You have given a number and you have to find out the kth least significant bit of this number. K will be given to you.  The bit will be from...

3 minutes read.

Why is Binary Heap Preferred over BST for Priority Queue

A priority queue is a linear and ordered collection of elements in which each element has an attribute named priority and the priority attribute decides the order in which elements...

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.

Find all possible words from board

We have been given a dictionary of words and a board of characters from which we can form strings. Now, we have to check if the string is present in...

5 minutes read.

Bubble Sort in Data Structures

Bubble Sort in C++ The bubble sort algorithm analyses two adjacent elements and swaps them until they are no longer in the desired order. Each iteration moves each member of the array...

4 minutes read.

Bin Packing Problem (How to minimize the number of used Bins)

You have been given an array. The values of the array represent the size of n different items. You have been also given some bins. You have to store the...

3 minutes read.

Radix Sort

Radix Sort: The radix sort is a non-comparative integer sorting algorithm that sorts the elements by grouping the individual digits of the same location. It shares the same significant position...

4 minutes read.

2-3 Trees and Basic Operations on them

2-3 Trees, like any other AVL trees or B-trees, are just a type of Height Balanced Tree. 2-3 Trees are the B-trees of order 3. Like every other B-tree, the...

4 minutes read.

Finding the Minimum and Maximum Value of a Binary Tree

Implementation // Writing a C++ program that will help us find out the maximum and the minimum in a binary tree.  #include <bits/stdc++.h> #include <iostream> using namespace std; // creating a new class tree node. class...

5 minutes read.

Linear Queue Data Structure in C

Data Structure There are many ways to store data in programming, that Queue has features that make it all the more special. We all know that data structure is a way...

9 minutes read.

What Should We Learn First? Trees or Graphs in Data Structures

A data structure is a database used to store and manage data and optimize and manage computing resources. A data structure is a form used intelligently and quickly to store,...

6 minutes read.

Berkley’s Algorithm

Berkley’s Algorithm is mainly used in clock synchronization system. It is used in distributed systems. To implement this algorithm, we have to think that the network has no accurate time...

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

Polish Notation in Data Structures

Arithmetic Expression: An arithmetic expression is defined as several operands or data items combined using several operators. For example; a+b*(c-d) is an expression. Operands: Operands represent the data in an expression...

2 minutes read.

Recursion in Fibonacci

Fibonacci heap is considered to be a particular execution of the heap data structure that ultimately helps in making use of not just any number but the Fibonacci numbers. It...

3 minutes read.

Bubble Sort vs Heap Sort

In this article, we are going to compare the two most common sorting techniques, Bubble Sort and Heap sort. Before discussing their differences, let us first discuss the idea of...

7 minutes read.

Deque in Data Structure

Deque A deque referred as “Double-Ended Queue”, is a linear collection of data items same like queue data structure. deque has two ends, front end and rear end, deque is the...

27 minutes read.

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 minutes read.

Length of longest palindrome in a linked list using O(1) extra space

Length of longest palindrome in a linked list using O(1) extra space In this problem, we need to find the length of the longest palindrome list that is present in given...

2 minutes read.

Symmetric binary tree

Implementation // writing a C++ program to check whether a given binary tree is symmetric or not. #include <bits/stdc++.h> using namespace std; // creating a binary tree node. struct __Nod { int ky; struct __Nod *Lft, *Rt; }; //...

4 minutes read.