Repository: TheAlgorithms/Java
Pull request #5386 (2024-08-24 20:56:38)

refactor: `ReverseStackUsingRecursion`
Class cleanup.
Readability improvements.
Added tests.

<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5386?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 47.03%. Comparing base [(`b231a72`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/b231a72d449420c6dc7004bc5969285aea7ec956?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`fd59eac`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/fd59eacb7683a6e4f9f962d84126a6f4b9ea928b?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5386      +/-   ##
============================================
+ Coverage     46.90%   47.03%   +0.12%     
- Complexity     2903     2909       +6     
============================================
  Files           525      525              
  Lines         15363    15351      -12     
  Branches       2908     2907       -1     
============================================
+ Hits           7206     7220      +14     
+ Misses         7855     7830      -25     
+ Partials        302      301       -1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5386?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/src/main/java/com/thealgorithms/others/ReverseStackUsingRecursion.java b/src/main/java/com/thealgorithms/others/ReverseStackUsingRecursion.java
index 2c26f8ea..de366735 100644
--- a/src/main/java/com/thealgorithms/others/ReverseStackUsingRecursion.java
+++ b/src/main/java/com/thealgorithms/others/ReverseStackUsingRecursion.java
@@ -1,63 +1,44 @@
 package com.thealgorithms.others;
 
-/* Program to reverse a Stack using Recursion*/
 import java.util.Stack;
 
+/**
+ * Class that provides methods to reverse a stack using recursion.
+ */
 public final class ReverseStackUsingRecursion {
     private ReverseStackUsingRecursion() {
     }
 
-    // Stack
-    private static Stack<Integer> stack = new Stack<>();
-
-    // Main function
-    public static void main(String[] args) {
-        // To Create a Dummy Stack containing integers from 0-9
-        for (int i = 0; i < 10; i++) {
-            stack.push(i);
-        }
-        System.out.println("STACK");
-
-        // To print that dummy Stack
-        for (int k = 9; k >= 0; k--) {
-            System.out.println(k);
+    /**
+     * Reverses the elements of the given stack using recursion.
+     *
+     * @param stack the stack to be reversed
+     * @throws IllegalArgumentException if the stack is null
+     */
+    public static void reverse(Stack<Integer> stack) {
+        if (stack == null) {
+            throw new IllegalArgumentException("Stack cannot be null");
         }
-
-        // Reverse Function called
-        reverseUsingRecursion(stack);
-
-        System.out.println("REVERSED STACK : ");
-        // To print reversed  stack
-        while (!stack.isEmpty()) {
-            System.out.println(stack.pop());
+        if (!stack.isEmpty()) {
+            int topElement = stack.pop();
+            reverse(stack);
+            insertAtBottom(stack, topElement);
         }
     }
 
-    // Function Used to reverse Stack Using Recursion
-    private static void reverseUsingRecursion(Stack<Integer> stack) {
-        if (stack.isEmpty()) { // If stack is empty then return
-            return;
-        }
-        /* All items are stored in call stack until we reach the end*/
-
-        int temptop = stack.peek();
-        stack.pop();
-        reverseUsingRecursion(stack); // Recursion call
-        insertAtEnd(temptop); // Insert items held in call stack one by one into stack
-    }
-
-    // Function used to insert element at the end of stack
-    private static void insertAtEnd(int temptop) {
+    /**
+     * Inserts an element at the bottom of the given stack.
+     *
+     * @param stack    the stack where the element will be inserted
+     * @param element  the element to be inserted at the bottom
+     */
+    private static void insertAtBottom(Stack<Integer> stack, int element) {
         if (stack.isEmpty()) {
-            stack.push(temptop); // If stack is empty push the element
+            stack.push(element);
         } else {
-            int temp = stack.peek();
-            /* All the items are stored in call stack until we reach end*/
-            stack.pop();
-
-            insertAtEnd(temptop); // Recursive call
-
-            stack.push(temp);
+            int topElement = stack.pop();
+            insertAtBottom(stack, element);
+            stack.push(topElement);
         }
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/others/ReverseStackUsingRecursionTest.java b/src/test/java/com/thealgorithms/others/ReverseStackUsingRecursionTest.java
new file mode 100644
index 00000000..23b99ae8
--- /dev/null
+++ b/src/test/java/com/thealgorithms/others/ReverseStackUsingRecursionTest.java
@@ -0,0 +1,58 @@
+package com.thealgorithms.others;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.Stack;
+import org.junit.jupiter.api.Test;
+
+public class ReverseStackUsingRecursionTest {
+
+    @Test
+    void testReverseWithMultipleElements() {
+        Stack<Integer> stack = new Stack<>();
+        for (int i = 0; i < 5; i++) {
+            stack.push(i);
+        }
+
+        ReverseStackUsingRecursion.reverse(stack);
+
+        for (int i = 0; i < 5; i++) {
+            assertEquals(i, stack.pop());
+        }
+        assertTrue(stack.isEmpty());
+    }
+
+    @Test
+    void testReverseWithSingleElement() {
+        Stack<Integer> stack = new Stack<>();
+        stack.push(1);
+
+        ReverseStackUsingRecursion.reverse(stack);
+
+        assertEquals(1, stack.pop());
+        assertTrue(stack.isEmpty());
+    }
+
+    @Test
+    void testReverseWithEmptyStack() {
+        Stack<Integer> stack = new Stack<>();
+
+        ReverseStackUsingRecursion.reverse(stack);
+
+        assertTrue(stack.isEmpty());
+    }
+
+    @Test
+    void testReverseWithNullStack() {
+        Stack<Integer> stack = null;
+
+        Exception exception = assertThrows(IllegalArgumentException.class, () -> ReverseStackUsingRecursion.reverse(stack));
+
+        String expectedMessage = "Stack cannot be null";
+        String actualMessage = exception.getMessage();
+
+        assertTrue(actualMessage.contains(expectedMessage));
+    }
+}