- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathPrefixToInfix.java
69 lines (58 loc) · 2.18 KB
/
PrefixToInfix.java
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
packagecom.thealgorithms.stacks;
importjava.util.Stack;
/**
* Converts a prefix expression to an infix expression using a stack.
*
* The input prefix expression should consist of
* valid operands (letters or digits) and operators (+, -, *, /, ^).
* Parentheses are not required in the prefix string.
*/
publicfinalclassPrefixToInfix {
privatePrefixToInfix() {
}
/**
* Determines if a given character is a valid arithmetic operator.
*
* @param token the character to check
* @return true if the character is an operator, false otherwise
*/
publicstaticbooleanisOperator(chartoken) {
returntoken == '+' || token == '-' || token == '/' || token == '*' || token == '^';
}
/**
* Converts a valid prefix expression to an infix expression.
*
* @param prefix the prefix expression to convert
* @return the equivalent infix expression
* @throws NullPointerException if the prefix expression is null
*/
publicstaticStringgetPrefixToInfix(Stringprefix) {
if (prefix == null) {
thrownewNullPointerException("Null prefix expression");
}
if (prefix.isEmpty()) {
return"";
}
Stack<String> stack = newStack<>();
// Iterate over the prefix expression from right to left
for (inti = prefix.length() - 1; i >= 0; i--) {
chartoken = prefix.charAt(i);
if (isOperator(token)) {
// Pop two operands from stack
StringoperandA = stack.pop();
StringoperandB = stack.pop();
// Form the infix expression with parentheses
Stringinfix = "(" + operandA + token + operandB + ")";
// Push the resulting infix expression back onto the stack
stack.push(infix);
} else {
// Push operand onto stack
stack.push(Character.toString(token));
}
}
if (stack.size() != 1) {
thrownewArithmeticException("Malformed prefix expression");
}
returnstack.pop(); // final element on the stack is the full infix expression
}
}