×

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

Bubble Sort vs Merge Sort

In this article, we are going to compare two sorting techniques, Bubble sort and Merge Sort. In starting, we will first discuss the idea of sorting an array using bubble...

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

Traversal of binary tree

Traversal of binary tree: A node is visited only once in the traversal of the binary tree. There are three main types of traversal methods in the binary tree. In-order traversalPre-order...

3 minutes read.

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.

Sorting Algorithms

Sorting: In the data structure, sorting is the process by which you arrange the data in a logical order. This logical order can also be an ascending order or a...

7 minutes read.

Cycle sort

Cycle sort is an examination arranging calculation which powers exhibit to be figured into the quantity of cycles where every one of them can be pivoted to create an arranged...

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

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.

Bottom view of the binary tree

The bottom of the binary tree is generally defined as the number of nods present in the bottom-most part of the tree. In this article, we will see the implementation...

3 minutes read.

Construction of B tree in Data Structure

A B-tree is a type of balanced tree data structure that is commonly used in file systems and databases to improve the efficiency of search, insert, and delete operations. The structure...

4 minutes read.

Preorder Traversal of Binary Trees

In general, Stack, Array, Queue, and other linear data structures only have one way to traverse the data. However, there are numerous ways to traverse through the data in a hierarchical...

3 minutes read.

Spanning Tree

Spanning Tree: The spanning tree is a subset of the graph. It is a non-cyclic graph. If any node in the spanning tree is truncated, the entire graph fails. There are...

10 minutes read.

Digital Search Tree in Data Structures

What is a digital search Tree in Data Structures? The Digital search tree is known for its application and diversity in the way it has impacted our world in the field...

3 minutes read.

Merge two sorted linked lists

Merge two sorted linked lists In this article, we are going to learn how to merge two linked lists. Here we have given two linked lists that are sorted in increasing...

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

Types of Data Structures

Almost every programme or software system that has been built makes use of data structures. Furthermore, data structures are basics of computer science and software engineering. When it comes to...

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

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.

Interval Tree

Interval Tree Interval Tree: The concept is to increase a Binary Search Tree self-balancing such as Red Black Tree, and AVL Tree, so that every feature can be completed in time O(Logn). Each Interval...

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.