×

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

Post-order traversal in a binary tree

We all know that postorder is a form of tree traversal to visit the tree's nodes, and it helps us reach out to the tree's nodes. Postorder means visiting the...

4 minutes read.

Trie data structure

Trie data structure The term “trie” comes from the word “retrieval” which means getting information. The trie data structure is a sorted extension of tree-based data structure. The trie data structure...

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

What is a Threaded Binary Tree?

When we consider those binary trees that are interlinked with each other, we do come across the fact that the fields present in there do consist of NULL values that...

3 minutes read.

Flatten Binary Tree to a linked list

Implementation In this section, we will see the implementation of the binary Tree and its conversion into linked lists. let us proceed: - // Writing a C++ program that will convert a...

4 minutes read.

Strings in Data Structures

Strings and functions in C A string is a collection of characters. We'll learn how to declare strings, operate with strings in C programming, and use pre-defined string handling routines. We'll look...

7 minutes read.

Linear Queue VS Circular Queue

What is Queue? A queue is one of the important linear data structures extensively used in various computer applications. It is based on the FIFO (First In First Out) principle. It...

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

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.

Circular Linked List

Circular Linked List A circular linked list where all nodes are connected to their next node and last node is connected to the starting node or we can say all nodes...

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

Common Operations on various Data Structures

Data structures are ways to organise data in computer memory for quick and effective use. The storage of data uses a variety of data-structures. It is also possible to define...

7 minutes read.

FLEX (Fast Lexical Analyzer Generator)

FLEX stands for Fast Lexical Analyzer Generator. Around 1987, Vern Paxson created Flex in C with a great deal of input and inspiration from Van Jacobson. Van Jacobson's approach is...

3 minutes read.

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

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

Queue Data Structure

Queue in DS: The queue is a non-primitive and linear data structure. It works on the principle of FIFO (First In First Out). That is, the element that is added...

4 minutes read.

Binary Tree vs Binary Search Tree: Data Structure

Difference Between Binary Tree and Binary Search Tree What is Binary Tree? A tree which each node can have utmost two children called binary tree. These children are referred as the ‘left...

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.

Quick Sort

Quicksort is a sorting algorithm that uses a divide-and-conquer strategy. A pivot element is used to divide an array into subarrays (element selected from the array).  The pivot element should be...

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.