Skip to content

Commit 5ee88f5

Browse files
authored
Add Infix to Postfix conversion using Stack
This program converts infix expressions to postfix notation using a stack. It includes operator precedence handling and supports basic arithmetic operators.
1 parent a0b6c52 commit 5ee88f5

File tree

1 file changed

+70
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)