-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfixToPrefixConverter.java
More file actions
98 lines (86 loc) · 3.3 KB
/
InfixToPrefixConverter.java
File metadata and controls
98 lines (86 loc) · 3.3 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import java.util.Stack;
public class InfixToPrefixConverter {
// Function to check if a character is an operator
private static boolean isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
// Function to get the precedence of an operator
private static int getPrecedence(char c) {
switch (c) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
// Function to reverse a string and swap parentheses
private static String reverseAndSwapParentheses(String expression) {
StringBuilder result = new StringBuilder();
for (int i = expression.length() - 1; i >= 0; i--) {
char c = expression.charAt(i);
if (c == '(') {
result.append(')');
} else if (c == ')') {
result.append('(');
} else {
result.append(c);
}
}
return result.toString();
}
// Function to convert infix expression to postfix
private static String infixToPostfix(String infix) {
StringBuilder postfix = new StringBuilder();
Stack<Character> stack = new Stack<>();
for (char c : infix.toCharArray()) {
// If the character is an operand, add it to the output
if (Character.isLetterOrDigit(c)) {
postfix.append(c);
}
// If the character is '(', push it to the stack
else if (c == '(') {
stack.push(c);
}
// If the character is ')', pop and output from the stack
// until an '(' is encountered
else if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix.append(stack.pop());
}
stack.pop();
}
// An operator is encountered
else if (isOperator(c)) {
while (!stack.isEmpty() && getPrecedence(c) <= getPrecedence(stack.peek())) {
postfix.append(stack.pop());
}
stack.push(c);
}
}
// Pop all the operators from the stack
while (!stack.isEmpty()) {
postfix.append(stack.pop());
}
return postfix.toString();
}
// Function to convert infix to prefix expression
public static String infixToPrefix(String infix) {
// Step 1: Reverse the infix expression and swap parentheses
String reversedInfix = reverseAndSwapParentheses(infix);
// Step 2: Convert reversed infix to postfix
String postfix = infixToPostfix(reversedInfix);
// Step 3: Reverse the postfix expression to get prefix
return new StringBuilder(postfix).reverse().toString();
}
public static void main(String[] args) {
String infixExpression = "(A+B)*C";
String prefixExpression = infixToPrefix(infixExpression);
System.out.println("Infix Expression: " + infixExpression);
System.out.println("Prefix Expression: " + prefixExpression);
}
}