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