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