-
Notifications
You must be signed in to change notification settings - Fork 0
/
InfixToPostfixConvertor.java
55 lines (49 loc) · 2.08 KB
/
InfixToPostfixConvertor.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
package calculator;
import java.util.Stack;
/*
* Convert infix expression to postfix expression.
*/
public class InfixToPostfixConvertor {
protected static String infixToPostfix(String[] input) {
String precedenceOrder = "+-/*^";
Stack<String> stack = new Stack<>();
StringBuilder postfixData = new StringBuilder();
for (String s : input) {
if (s.matches("[A-Za-z\\d]+")) {
postfixData.append(s.concat(" "));
} else {
String top = !stack.empty() ? stack.peek() : "";
if (s.equals("(")
|| stack.empty()
|| top.equals("(")
|| precedenceOrder.indexOf(top) < precedenceOrder.indexOf(s)) {
stack.push(s);
} else {
if (s.equals(")")) {
while (!top.equals("(")) {
String stackValue = !stack.empty() ? stack.pop() : "";
stackValue = stackValue.equals("(") ? "" : stackValue.concat(" ");
postfixData.append(stackValue);
top = !stack.empty() ? stack.peek() : "";
}
stack.pop();
} else {
while (!top.equals("") && precedenceOrder.indexOf(top) >= precedenceOrder.indexOf(s)) {
String stackValue = !stack.empty() ? stack.pop() : "";
stackValue = stackValue.equals("(") ? "" : stackValue.concat(" ");
postfixData.append(stackValue);
top = !stack.empty() ? stack.peek() : "";
}
stack.push(s);
}
}
}
}
while (!stack.empty()) {
String stackValue = stack.pop();
stackValue = stackValue.equals("(") ? "" : stackValue.concat(" ");
postfixData.append(stackValue);
}
return postfixData.toString();
}
}