Skip to content

Instantly share code, notes, and snippets.

@humayun0156
Last active March 11, 2016 13:41
Show Gist options
  • Save humayun0156/7b5d800d341f30541f3b to your computer and use it in GitHub Desktop.
Save humayun0156/7b5d800d341f30541f3b to your computer and use it in GitHub Desktop.
Shunting-yard algorithm
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* @author humayun
*
* https://en.wikipedia.org/wiki/Shunting-yard_algorithm
*
*/
public class ShuntingYardAlgorithm {
public static void main(String[] args) {
String infix = "3+4*2/(1-5)";
String output = new ShuntingYardAlgorithm().shuntingYard(infix);
System.out.println(output);
}
private enum Operator {
ADD(1), SUBTRACT(2), MULTIPLY(3), DIVIDE(4);
final int precedence;
Operator(int p) {
precedence = p;
}
}
private Map<String, Operator> operatorMap = new HashMap<String, Operator>() {{
put("+", Operator.ADD);
put("-", Operator.SUBTRACT);
put("*", Operator.MULTIPLY);
put("/", Operator.DIVIDE);
}};
private boolean isHigherPrec(String op, String sub) {
return (operatorMap.containsKey(sub) &&
operatorMap.get(sub).precedence >= operatorMap.get(op).precedence);
}
public String shuntingYard(String infix) {
StringBuilder output = new StringBuilder();
Stack<String> stack = new Stack<String>();
for (String token : infix.split("")) {
//operator
if (operatorMap.containsKey(token)) {
while ( ! stack.isEmpty() && isHigherPrec(token, stack.peek())) {
output.append(stack.pop()).append(' ');
}
stack.push(token);
}
//left parenthesis
else if (token.equals("(")) {
stack.push(token);
}
//right parenthesis
else if (token.equals(")")) {
while ( ! stack.peek().equals("(")) {
output.append(stack.pop()).append(' ');
}
stack.pop();
}
//digit
else {
output.append(token).append(' ');
}
}
while ( ! stack.isEmpty()) {
output.append(stack.pop()).append(' ');
}
return output.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment