-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathInfixToPostfixConverter.java
More file actions
69 lines (57 loc) · 2.1 KB
/
InfixToPostfixConverter.java
File metadata and controls
69 lines (57 loc) · 2.1 KB
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 convertor;
import java.util.Arrays;
import java.util.Stack;
import operator.Operator;
import util.PatternValidator;
public class InfixToPostfixConverter {
private StringBuilder postfix = new StringBuilder();
public String changeToPostFix(String expression) {
Stack<String> operatorStack = new Stack();
String[] splitExpression = expression.split(" ");
Arrays.stream(splitExpression).forEach(token -> {
processToken(operatorStack, token);
});
while (!operatorStack.isEmpty()) {
postfix.append(operatorStack.pop());
}
return postfix.toString();
}
private void processToken(Stack<String> operatorStack, String token) {
if (PatternValidator.checkOperatorValue(token)) {
handleOperator(operatorStack, token);
} else if (!PatternValidator.checkOperatorValue(token)) {
handelOperand(token);
}
}
private void handelOperand(String token) {
int value = Integer.parseInt(token);
postfix.append(value).append(" ");
}
private void handleOperator(Stack<String> operatorStack, String token) {
Operator currentOperator = Operator.stringToOperator(token);
int currentOperatorPriority = operatorPriority(currentOperator);
setOperatorToOperatorStack(operatorStack, token,currentOperatorPriority);
}
private void setOperatorToOperatorStack(Stack<String> operatorStack, String token,int currentOperatorPriority) {
compareOperatorPriority(operatorStack,currentOperatorPriority);
operatorStack.add((token + " "));
}
private void compareOperatorPriority(Stack<String> operatorStack,int currentOperatorPriority) {
Operator topStackOperator = Operator.stringToOperator(operatorStack.peek().substring(0, 1));
int topStackOperatorPriority = operatorPriority(topStackOperator);
while (!operatorStack.isEmpty() && topStackOperatorPriority >= currentOperatorPriority) {
postfix.append(operatorStack.pop());
}
}
public int operatorPriority(Operator operator) {
switch (operator) {
case PLUS:
case MINUS:
return 1;
case MULTIPLY:
case DIVIDE:
return 2;
}
return -1;
}
}