1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
package bjc.utils.parserutils;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.function.Function;
import bjc.utils.funcdata.FunctionalList;
public class ShuntingYard<E> {
private enum Operator {
ADD(1), SUBTRACT(2), MULTIPLY(3), DIVIDE(4);
final int precedence;
Operator(int p) {
precedence = p;
}
}
private static Map<String, Operator> ops = new HashMap<String, Operator>();
static {
ops.put("+", Operator.ADD);
ops.put("-", Operator.SUBTRACT);
ops.put("*", Operator.MULTIPLY);
ops.put("/", Operator.DIVIDE);
}
private boolean isHigherPrec(String op, String sub) {
return (ops.containsKey(sub)
&& ops.get(sub).precedence >= ops.get(op).precedence);
}
public FunctionalList<E> postfix(FunctionalList<String> inp,
Function<String, E> transform) {
FunctionalList<E> outp = new FunctionalList<>();
Deque<String> stack = new LinkedList<>();
inp.forEach((token) -> {
if (ops.containsKey(token)) {
while (!stack.isEmpty()
&& isHigherPrec(token, stack.peek())) {
outp.add(transform.apply(stack.pop()));
}
stack.push(token);
} else if (token.equals("(")) {
stack.push(token);
} else if (token.equals(")")) {
while (!stack.peek().equals("(")) {
outp.add(transform.apply(stack.pop()));
}
stack.pop();
} else {
outp.add(transform.apply(token));
}
});
while (!stack.isEmpty()) {
outp.add(transform.apply(stack.pop()));
}
return outp;
}
}
|