Skip to content

Commit 4e8d553

Browse files
authored
Add Infix to Postfix conversion implementation
Infix Expression: Operator is between operands → A + B Postfix Expression: Operator is after operands → A B + We use a stack to temporarily hold operators and handle operator precedence.
1 parent a0b6c52 commit 4e8d553

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import java.util.Stack;
2+
3+
public class InfixToPostfix {
4+
5+
// Function to check operator precedence
6+
static int precedence(char ch) {
7+
switch (ch) {
8+
case '+':
9+
case '-':
10+
return 1;
11+
case '*':
12+
case '/':
13+
return 2;
14+
case '^':
15+
return 3;
16+
}
17+
return -1;
18+
}
19+
20+
// Function to convert infix to postfix
21+
static String convert(String expression) {
22+
String result = "";
23+
Stack<Character> stack = new Stack<>();
24+
25+
for (int i = 0; i < expression.length(); i++) {
26+
char c = expression.charAt(i);
27+
28+
// If character is an operand, add it to output
29+
if (Character.isLetterOrDigit(c)) {
30+
result += c;
31+
}
32+
33+
// If character is '(', push it to stack
34+
else if (c == '(') {
35+
stack.push(c);
36+
}
37+
38+
// If character is ')', pop until '(' is found
39+
else if (c == ')') {
40+
while (!stack.isEmpty() && stack.peek() != '(') {
41+
result += stack.pop();
42+
}
43+
stack.pop(); // remove '('
44+
}
45+
46+
// If character is operator
47+
else {
48+
while (!stack.isEmpty() && precedence(c) <= precedence(stack.peek())) {
49+
result += stack.pop();
50+
}
51+
stack.push(c);
52+
}
53+
}
54+
55+
// Pop all remaining operators from stack
56+
while (!stack.isEmpty()) {
57+
result += stack.pop();
58+
}
59+
60+
return result;
61+
}
62+
63+
// Main method to test the program
64+
public static void main(String[] args) {
65+
String infix = "A*(B+C)/D";
66+
System.out.println("Infix: " + infix);
67+
System.out.println("Postfix: " + convert(infix));
68+
}
69+
}

0 commit comments

Comments
 (0)