Posts

Search

02x10 - Infix to Postfix

A postfix expression is of the form instead of the traditional infix expression which follows the form .

Your task is to write a program that takes advantage of the stack data structure and converts a given infix expression into its postfix expression.

INPUT

There will be only a single line of input, the string that denotes the infix expression to be converted into its postfix counterpart.

There are four arithmetic operations and capital letters used as variables/operands.

Look at the sample Input/Output for clarity

OUTPUT

Output the final postfix expression after converting it to postfix from infix.

Sample Input 0

A+B

Sample Output 0

AB+


Solution:

import java.util.Stack;
import java.util.*;
  
class Solution 
    static int Prec(char ch) 
    { 
        switch (ch) 
        { 
        case '+': 
        case '-': 
            return 1; 
       
        case '*': 
        case '/': 
            return 2; 
       
        case '^': 
            return 3; 
        } 
        return -1; 
    } 
    static String infixToPostfix(String exp) 
    { 
        String result = new String(""); 
        Stack<Character> stack = new Stack<>(); 
          
        for (int i = 0; i<exp.length(); ++i) 
        { 
            char c = exp.charAt(i); 
            if (Character.isLetterOrDigit(c)) 
                result += c; 
            else if (c == '(') 
                stack.push(c); 
            else if (c == ')') 
            { 
                while (!stack.isEmpty() && stack.peek() != '(') 
                    result += stack.pop(); 
                  
                if (!stack.isEmpty() && stack.peek() != '(') 
                    return "Invalid Expression";              
                else
                    stack.pop(); 
            } 
            else 
            { 
                while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek())){ 
                    if(stack.peek() == '(') 
                        return "Invalid Expression"; 
                    result += stack.pop(); 
             } 
                stack.push(c); 
            } 
       
        } 
        while (!stack.isEmpty()){ 
            if(stack.peek() == '(') 
                return "Invalid Expression"; 
            result += stack.pop(); 
         } 
        return result; 
    } 
    public static void main(String[] args)  
    { 
        Scanner sc=new Scanner(System.in);
        String exp = sc.next(); 
        System.out.println(infixToPostfix(exp)); 
    }