Skip to content

Commit 6faa2e3

Browse files
infix to postfix
1 parent 2e6c7b4 commit 6faa2e3

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package DataStructures.Stacks;
2+
3+
import java.util.Stack;
4+
5+
public class InfixToPostfix {
6+
public static void main(String[] args) throws Exception {
7+
assert "32+".equals(infix2PostFix("3+2"));
8+
assert "123++".equals(infix2PostFix("1+(2+3)"));
9+
assert "34+5*6-".equals(infix2PostFix("(3+4)*5-6"));
10+
}
11+
12+
public static String infix2PostFix(String infixExpression) throws Exception {
13+
if (!BalancedBrackets.isBalanced(infixExpression)) {
14+
throw new Exception("invalid expression");
15+
}
16+
StringBuilder output = new StringBuilder();
17+
Stack<Character> stack = new Stack<>();
18+
for (char element : infixExpression.toCharArray()) {
19+
if (Character.isLetterOrDigit(element)) {
20+
output.append(element);
21+
} else if (element == '(') {
22+
stack.push(element);
23+
} else if (element == ')') {
24+
while (!stack.isEmpty() && stack.peek() != '(') {
25+
output.append(stack.pop());
26+
}
27+
stack.pop();
28+
} else {
29+
while (!stack.isEmpty() && precedence(element) <= precedence(stack.peek())) {
30+
output.append(stack.pop());
31+
}
32+
stack.push(element);
33+
}
34+
}
35+
while (!stack.isEmpty()) {
36+
output.append(stack.pop());
37+
}
38+
return output.toString();
39+
}
40+
41+
private static int precedence(char operator) {
42+
switch (operator) {
43+
case '+':
44+
case '-':
45+
return 0;
46+
case '*':
47+
case '/':
48+
return 1;
49+
case '^':
50+
return 2;
51+
default:
52+
return -1;
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)