Skip to content

Commit b74c67c

Browse files
committed
Refactored ReverseStringUsingStack utility for reversing strings using stack
1 parent a1a05a1 commit b74c67c

File tree

3 files changed

+9
-1
lines changed

3 files changed

+9
-1
lines changed

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ private ReverseStringUsingStack() {
1111
* @return reversed string
1212
*/
1313
public static String reverse(String str) {
14+
// Check if the input string is null
15+
if (str == null) {
16+
throw new IllegalArgumentException("Input string cannot be null");
17+
}
1418
Stack<Character> stack = new Stack<>();
1519
StringBuilder reversedString = new StringBuilder();
1620
// Check if the input string is empty

src/main/java/com/thealgorithms/strings/ReverseString.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,12 +59,16 @@ public static String reverse3(String string) {
5959
}
6060
return sb.toString();
6161
}
62+
6263
/**
6364
* Reverse version 4 the given string using a Stack.
6465
* This method pushes each character of the string onto a stack
6566
* and then pops them off to create the reversed string.
6667
*/
6768
public static String reverse4(String str) {
69+
if (str == null) {
70+
throw new IllegalArgumentException("Input string cannot be null");
71+
}
6872
Stack<Character> stack = new Stack<>();
6973
StringBuilder reversedString = new StringBuilder();
7074
// Check if the input string is empty

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,6 @@ void testWhitespaceHandling() {
3939

4040
@Test
4141
void testNullInput() {
42-
assertThrows(NullPointerException.class, () -> { ReverseStringUsingStack.reverse(null); });
42+
assertThrows(IllegalArgumentException.class, () -> { ReverseStringUsingStack.reverse(null); });
4343
}
4444
}

0 commit comments

Comments
 (0)