Created
May 6, 2020 22:38
-
-
Save TheGloriousGenesis/83930a6c17410172e600f963aec5c0e3 to your computer and use it in GitHub Desktop.
InfixToPostFix conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static String infixToPostfix(final String equation){ | |
Stack<Character> stack = new Stack<Character>(); | |
StringBuilder postFixNotation = new StringBuilder(); | |
HashMap<Character, Integer> operators = new HashMap<>(); | |
operators.put('^', 5); | |
operators.put('/', 4); | |
operators.put('*', 3); | |
operators.put('+', 2); | |
operators.put('-', 1); | |
operators.put('(', 0); | |
Set<Character> operator = operators.keySet(); | |
int pointer = 0; | |
char[] equationChars = equation.toCharArray(); | |
while (pointer < equationChars.length) { | |
if (equationChars[pointer] == ')'){ | |
for (int i=0; i < stack.size() - 1; i++) { | |
postFixNotation.append(stack.pop()); | |
} | |
pointer++; | |
boolean checkNextCharContainsOperator = operators.containsKey(equationChars[pointer]); | |
if (checkNextCharContainsOperator && | |
operators.get(stack.peek()) > operators.get(equationChars[pointer])) { | |
postFixNotation.append(stack.pop()); | |
stack.push(equationChars[pointer]); | |
} | |
pointer++; | |
continue; | |
} | |
if (operator.contains(equationChars[pointer])) { | |
stack.push(equationChars[pointer]); | |
} else if (equationChars[pointer] != '('){ | |
postFixNotation.append(equationChars[pointer]); | |
} | |
pointer++; | |
} | |
for (int i=0; i< stack.size(); i++) { | |
postFixNotation.append(stack.pop()); | |
} | |
return postFixNotation.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment