Write a program convert Postfix to Infix using stack
Example 1:
Input: postfix = "ABC*+EF/GH^*+"
Output: infix="A+B*C+E/F*G^H"
Approach
Java
import java.util.HashMap;import java.util.Stack;public class PostfixToInfix {public static void main(String[] args) {// postfixString postFIx = "ABC*+EF/GH^*+";// postfix to infixString infix = postfixToInfix(postFIx);System.out.println("Infix is " + infix);}private static String postfixToInfix(String postFIx) {String infix = "";// stack for hold operatorStack<String> stack = new Stack<>();// Iterate till given postfix lengthfor (int i = 0; i < postFIx.length(); i++) {// hold char from postFIxchar c = postFIx.charAt(i);// If letter then add into stackif (Character.isLetter(c)) {stack.add(String.valueOf(c));} else {// rule = second+operator+firstString a = stack.pop();String b = stack.pop();stack.add(b + "" + c + "" + a);}}// iterate till stack is emptywhile (!stack.isEmpty()) {infix += stack.pop();}return infix;}}
C++
#include <bits/stdc++.h>using namespace std;//unction to convert from//postfix to infixstring postfixToInfix(string postFIx){string infix = "";//stack for hold operatorstack<string> stack;// Iterate till given postfix lengthfor (int i = 0; i < postFIx.size(); i++){//hold char from postFIxchar c = postFIx[i];// If letter then add into stackif (isalpha(c)){//convert from character//to stringstring strc(1,c);stack.push(strc);}else{// rule = second+operator+firststring a = stack.top();stack.pop();string b = stack.top();stack.pop();//convert from character//to stringstring strc(1,c);stack.push(b + "" + strc + "" + a);}}//iterate till stack is emptywhile (!stack.empty()) {{infix += stack.top();stack.pop();}}return infix;}int main(){// postfixstring postFIx = "ABC*+EF/GH^*+";//postfix to infixstring infix = postfixToInfix(postFIx);cout<<"Infix is ";cout<<infix<<"\n";return 0;}
No comments:
Post a Comment