Prefix to Postfix Conversion in C++

C++Server Side ProgrammingProgramming

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

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

Example: +AB.

Postfix expressions are those expressions which have operators after operands in the expressions.

Example: AB/

The conversion of prefix to postfix should not involve the conversion to infix.

Let’s take an example to understand the problem,

Input: /+XY+NM
Output: XY+NM+/
Explanation: infix -> (X+Y)/(N+M)

To solve this problem, we will first traverse the whole postfix expression in an reverse order. And we will be using the stack data structure for our processing. And do the following for cases of elements found of traversal

Case: if the symbol is operand -> push(element) in stack.

Case: if symbol is operator -> 2*pop(element) from stack. And then push sequence of operand - operand - operator.

Program to show the implementation of our algorithm

Example

 Live Demo

#include <iostream>
#include <stack>
using namespace std;
bool isOperator(char x) {
   switch (x) {
      case '+':
      case '-':
      case '/':
      case '*':
      return true;
   }
   return false;
}
string convertToPostfix(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 + op2 + prefix[i];
         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<<"Postfix expression : "<<convertToPostfix(prefix);
   return 0;
}

Output

Prefix expression : *-AB/+CD*XY
Postfix expression : AB-CD+XY*/*
raja
Published on 03-Feb-2020 12:10:11
Advertisements