Prefix to Infix Conversion in C++


In this problem, we are given a prefix expression. Our task is to print the infix conversion of the given expression.

Prefix expression is those expressions which have operators before the operands.

Example: +AB.

Infix expressions are those expressions which have operators between the operands.

Example: A+B

Infix expression are information for human understanding, but the computer does computations on prefix or postfix expressions (generally postfix).

Let’s take an example to understand the problem

Input: prefix : /+LM/NX
Output: infix : (L+M) / (N/X)

To solve this problem, we will be using the stack data structure. We will traverse the prefix expression in reverse order of the expression. And for each element of the expression check for these cases.

If element is operand -> push(element) in stack.

If element is operator -> 2Xpop(topofstack) and push in order as a string = operand - operator - operand.

Finally, after traversal, the top of the stack will contain a string which is the infix conversion, print it.

Program to show the implementation of our solution

Example

 Live Demo

#include <iostream>
#include <stack>
using namespace std;
bool isOperator(char element) {
   switch (element) {
      case '+':
      case '-':
      case '/':
      case '*':
      return true;
   }
   return false;
}
string convertToInfix(string prefix) {
   stack<string> expression;
   int length = prefix.size();
   for (int i = length - 1; i >= 0; i--) {
      if (isOperator(prefix[i])) {
         string op1 = expression.top();
         expression.pop();
         string op2 = expression.top();
         expression.pop();
         string temp = "{"+op1+prefix[i]+op2+"}";
         expression.push(temp);
      } else {
         expression.push(string(1, prefix[i]));
      }
   }
   return expression.top();
}
int main() {
   string prefix = "*-AB/+CD*XY";
   cout<<"Prefix expression : "<<prefix<<endl;
   cout<<"Infix expression : " <<convertToInfix(prefix);
   return 0;
}

Output

Prefix expression : *-AB/+CD*XY
Infix expression : {{A-B}*{{C+D}/{X*Y}}}

Updated on: 03-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements