Stack: Postfix to infix expression

Question: Convert Postfix to infix expression

Resources: https://www.youtube.com/watch?v=1zqgyoZzda4&list=PLdo5W4Nhv31bbKJzrsKfMpo_grxuLl8LU&index=38

package additional_problems.stack;

/**
 * 1. If operand is encountered then store in stack
 * 2. If operator occurs then pop top two elements and join them using the operator. Add parenthesis around the expression
 * 3. Push result onto the stack
 * 4. Once the entire expression is traversed, return the top of the stack
 * Created by aarushi on 7/7/21.
 */
public class P07PostfixToInfix {

    //method to combine operators and operands
    public static String combineExpression(char operator, String operand1, String operand2){
        return "("+operand1+Character.toString(operator)+operand2+")";
    }

    //method to convert postfix expression to infix expression
    public static String postfixToInfix(String postfixExpression){
        StringStack stack= new StringStack(postfixExpression.length());

        for (int i=0; i<postfixExpression.length(); i++){
            char c= postfixExpression.charAt(i);

            //1. If operand is encountered then store in stack
            if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
                stack.push(Character.toString(c));
            }

            //2. If operator occurs then pop top two elements and join them using the operator. Add parenthesis around the expression
            else if(c=='+' || c=='-' || c=='*' || c=='/' || c=='%' | c=='^'){
                //3. Push result onto the stack
                stack.push(combineExpression(c, stack.pop(), stack.pop()));
            }
        }

        //4. Once the entire expression is traversed, return the top of the stack
        return stack.pop();
    }


    public static String reverseString(String string){
        StringBuffer reversedString= new StringBuffer("");
        for (int i = string.length()-1; i >=0; i--) {
            if(string.charAt(i)=='('){
                reversedString.append(')');
            } else if(string.charAt(i)==')'){
                reversedString.append('(');
            } else{
                reversedString.append(string.charAt(i));
            }
        }
        return reversedString.toString();
    }

    public static void main(String [] args){
        String postfixExpression= "ab*c+";
        System.out.println(reverseString(postfixToInfix(postfixExpression)));
    }

}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close