Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,19 @@ private ReverseStack() {
*
* @param stack the stack to reverse; should not be null
*/
public static void reverseStack(Stack<Integer> stack) {
if (stack.isEmpty()) {
return;
}

int element = stack.pop();
reverseStack(stack);
insertAtBottom(stack, element);
public static void reverseStack(Stack<Integer> stack) {
if (stack == null) {
throw new IllegalArgumentException("Stack cannot be null");
}
if (stack.isEmpty()) {
return;
}

int element = stack.pop();
reverseStack(stack);
insertAtBottom(stack, element);
}


/**
* Inserts the specified element at the bottom of the stack.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
package com.thealgorithms.datastructures.stacks;

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;

class ReverseStackTest {

@Test
void testReverseNullStack() {
assertThrows(IllegalArgumentException.class,
() -> ReverseStack.reverseStack(null),
"Reversing a null stack should throw an IllegalArgumentException.");
}


@Test
void testReverseEmptyStack() {
Stack<Integer> stack = new Stack<>();
Expand Down