Skip to content

Commit 3d83d6f

Browse files
authored
Implement Infix to Postfix conversion algorithm
Implement Infix to Postfix conversion algorithm using stack library
1 parent ade777a commit 3d83d6f

File tree

1 file changed

+65
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)