Skip to content

Commit 4de9a22

Browse files
committed
Add suggested changes
1 parent 5f14ff3 commit 4de9a22

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

src/main/java/com/thealgorithms/stacks/PrefixToInfix.java

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,12 @@
33
import java.util.Stack;
44

55
/**
6-
* Prefix to Infix implementation via Stack
6+
* Converts a prefix expression to an infix expression using a stack.
77
*
8-
* Function: String getPrefixToInfix(String prefix)
9-
* Returns the Infix Expression for the given prefix parameter.
10-
*
11-
* Avoid using parentheses/brackets/braces for the prefix string.
12-
* Prefix Expressions don't require these.
8+
* The input prefix expression should consist of
9+
* valid operands (letters or digits) and operators (+, -, *, /, ^).
10+
* Parentheses are not required in the prefix string.
1311
*/
14-
1512
public final class PrefixToInfix {
1613
private PrefixToInfix() {
1714
}
@@ -63,6 +60,10 @@ public static String getPrefixToInfix(String prefix) {
6360
}
6461
}
6562

63+
if (stack.size() != 1) {
64+
throw new ArithmeticException("Malformed prefix expression");
65+
}
66+
6667
return stack.pop(); // final element on the stack is the full infix expression
6768
}
6869
}

src/test/java/com/thealgorithms/stacks/PrefixToInfixTest.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,9 @@ void testEmptyPrefixExpression() {
3636
void testNullPrefixExpression() {
3737
assertThrows(NullPointerException.class, () -> PrefixToInfix.getPrefixToInfix(null));
3838
}
39+
40+
@Test
41+
void testMalformedPrefixExpression() {
42+
assertThrows(ArithmeticException.class, () -> PrefixToInfix.getPrefixToInfix("+ABC"));
43+
}
3944
}

0 commit comments

Comments
 (0)