In: Computer Science
//Code Link => https://repl.it/@FAYAZPASHA/InnocentAgonizingQuote#Main.java
import java.util.Stack;
import java.util.*;
class Main
{
static int Precdence(char ch) //returns the character priority
{
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
static String infixToPostfix(String exp)
{
// initializing empty String for result
String result = new String("");
// initializing empty stack
Stack<Character> stack = new Stack<>();
for (int i = 0; i<exp.length(); ++i)
{
char c = exp.charAt(i);
// If the scanned character is an operand, add it to output.
if (Character.isLetterOrDigit(c)) //if we encounter a operand we append to our results
result += c;
else if (c == '(') //if we encountered a opening parenthesis we push it to the stack
stack.push(c);
else if (c == ')') // when we encounter a closing parenthesis we check for the priority of the operator residing inside the stack
{
while (!stack.isEmpty() && stack.peek() != '(')
result += stack.pop();
if (!stack.isEmpty() && stack.peek() != '(')
return "Invalid Expression"; // invalid expression
else
stack.pop();
}
else // an operator is encountered
{
while (!stack.isEmpty() && Precdence(c) <= Precdence(stack.peek())){
if(stack.peek() == '(')
return "Invalid Expression";
result += stack.pop();
}
stack.push(c);
}
}
// pop all the operators from the stack
while (!stack.isEmpty()){
if(stack.peek() == '(')
return "Invalid Expression";
result += stack.pop();
}
return result;
}
// Driver method
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String exp = sc.nextLine();
// String exp = "a+b*(c^d-e)^(f+g*h)-i";
System.out.println(infixToPostfix(exp));
}
}