forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfixToPostfixevaluator.java
More file actions
69 lines (58 loc) · 1.83 KB
/
InfixToPostfixevaluator.java
File metadata and controls
69 lines (58 loc) · 1.83 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
import java.util.Stack;
public class InfixToPostfix {
// Function to check operator precedence
static int precedence(char ch) {
switch (ch) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
// Function to convert infix to postfix
static String convert(String expression) {
String result = "";
Stack<Character> stack = new Stack<>();
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
// If character is an operand, add it to output
if (Character.isLetterOrDigit(c)) {
result += c;
}
// If character is '(', push it to stack
else if (c == '(') {
stack.push(c);
}
// If character is ')', pop until '(' is found
else if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
result += stack.pop();
}
stack.pop(); // remove '('
}
// If character is operator
else {
while (!stack.isEmpty() && precedence(c) <= precedence(stack.peek())) {
result += stack.pop();
}
stack.push(c);
}
}
// Pop all remaining operators from stack
while (!stack.isEmpty()) {
result += stack.pop();
}
return result;
}
// Main method to test the program
public static void main(String[] args) {
String infix = "A*(B+C)/D";
System.out.println("Infix: " + infix);
System.out.println("Postfix: " + convert(infix));
}
}