-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShuntingYard.java
76 lines (63 loc) · 2.01 KB
/
ShuntingYard.java
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
70
71
72
73
74
75
76
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class ShuntingYard {
// Map to maintain the operators precedence values.
Map<Character, Integer> precedence = new HashMap<Character, Integer>();
Stack<Character> operators = new Stack<Character>();
char tokens;
// Adding precedence values for operators.
public ShuntingYard() {
precedence.put('!', 4);
precedence.put('*', 2);
precedence.put('/', 2);
precedence.put('+', 1);
precedence.put('-', 1);
precedence.put('^', 3);
}
// Helper function to check if the operand is valid or not.
private boolean validOperand(char token) {
return ((token >= 'A') && (token <= 'Z')) || ((token >= 'a') && (token <= 'z'))
|| ((token >= '0') && (token <= '9'));
}
// Helper function to check the precedence of the operator being added
private boolean checkPrecedence(char token, char topElement) {
if (precedence.containsKey(topElement)) {
return precedence.get(topElement) >= precedence.get(token);
} else
return false;
}
public StringBuilder shuntingUtil(String infixNotation) {
StringBuilder outputQueue = new StringBuilder();
for (int i = 0; i < infixNotation.length(); i++) {
tokens = infixNotation.charAt(i);
if (tokens == ' ')
continue;
if (precedence.containsKey(tokens)) {
while (!operators.isEmpty() && checkPrecedence(tokens, operators.peek())) {
// outputQueue.offer(operators.pop());
outputQueue.append(operators.pop());
}
operators.push(tokens);
} else if (tokens == '(') {
operators.push(tokens);
} else if (tokens == ')') {
while (operators.peek() != '(') {
// outputQueue.offer(operators.pop());
outputQueue.append(operators.pop());
}
operators.pop();
} else if (validOperand(tokens)) {
outputQueue.append(tokens);
} else {
System.out.println("Invalid operands");
System.exit(0);
}
}
while (!operators.isEmpty()) {
// outputQueue.offer(operators.pop());
outputQueue.append(operators.pop());
}
return outputQueue;
}
}