Skip to content

Commit 87291d7

Browse files
authored
Add Infix to Postfix conversion class (#3554)
2 parents 2428d5f + 90dcd5a commit 87291d7

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

fineanmol

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import java.util.Stack;
2+
3+
public class InfixToPostfix {
4+
5+
// function to return precedence of operators
6+
static int precedence(char ch) {
7+
switch (ch) {
8+
case '+':
9+
case '-':
10+
return 1;
11+
case '*':
12+
case '/':
13+
case '%':
14+
return 2;
15+
case '^':
16+
return 3;
17+
}
18+
return -1;
19+
}
20+
21+
// function to convert infix to postfix
22+
public static String convert(String infix) {
23+
Stack<Character> stack = new Stack<>();
24+
StringBuilder postfix = new StringBuilder();
25+
26+
for (int i = 0; i < infix.length(); i++) {
27+
28+
char ch = infix.charAt(i);
29+
30+
// 1. Operand → directly add
31+
if (Character.isLetterOrDigit(ch)) {
32+
postfix.append(ch);
33+
}
34+
35+
// 2. '(' → push to stack
36+
else if (ch == '(') {
37+
stack.push(ch);
38+
}
39+
40+
// 3. ')' → pop until '('
41+
else if (ch == ')') {
42+
while (!stack.isEmpty() && stack.peek() != '(') {
43+
postfix.append(stack.pop());
44+
}
45+
stack.pop(); // remove '('
46+
}
47+
48+
// 4. Operator
49+
else {
50+
while (!stack.isEmpty() &&
51+
precedence(ch) <= precedence(stack.peek())) {
52+
53+
// exception for '^' (right associative)
54+
if (ch == '^' && stack.peek() == '^')
55+
break;
56+
57+
postfix.append(stack.pop());
58+
}
59+
stack.push(ch);
60+
}
61+
}
62+
63+
// pop all remaining operators
64+
while (!stack.isEmpty()) {
65+
postfix.append(stack.pop());
66+
}
67+
68+
return postfix.toString();
69+
}
70+
71+
public static void main(String[] args) {
72+
String infix = "A+(B*C-(D/E^F)*G)*H";
73+
System.out.println("Postfix: " + convert(infix));
74+
}
75+
}

0 commit comments

Comments
 (0)