Skip to content

Instantly share code, notes, and snippets.

@shahril96
Created February 19, 2016 06:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shahril96/a0740a77053010b5d96d to your computer and use it in GitHub Desktop.
Save shahril96/a0740a77053010b5d96d to your computer and use it in GitHub Desktop.
Infix to Postfix - Java Converter (no invalid expressions checking)
import java.util.*;
public class postfix {
public static void main(String args[]) {
String infix = "x-(y*a/b-(z+d*e)+c)/f";
System.out.println("Infix : " + infix);
System.out.println("Postfix : " + inf2postf(infix));
}
private static String inf2postf(String infix) {
String postfix = "";
Stack<Character> operator = new Stack<Character>();
char popped;
for (int i = 0; i < infix.length(); i++) {
char get = infix.charAt(i);
if (!isOperator(get))
postfix += get;
else if (get == ')')
while ((popped = operator.pop()) != '(')
postfix += popped;
else {
while (!operator.isEmpty() && get != '(' && precedence(operator.peek()) >= precedence(get))
postfix += operator.pop();
operator.push(get);
}
}
// pop any remaining operator
while (!operator.isEmpty())
postfix += operator.pop();
return postfix;
}
private static boolean isOperator(char i) {
return precedence(i) > 0;
}
private static int precedence(char i) {
if (i == '(' || i == ')') return 1;
else if (i == '-' || i == '+') return 2;
else if (i == '*' || i == '/') return 3;
else return 0;
}
}
@R1zarD9K
Copy link

Thank You Sir!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment