File tree Expand file tree Collapse file tree
main/java/com/thealgorithms/datastructures/stacks
test/java/com/thealgorithms/datastructures/stacks Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -37,15 +37,19 @@ private ReverseStack() {
3737 *
3838 * @param stack the stack to reverse; should not be null
3939 */
40- public static void reverseStack (Stack <Integer > stack ) {
41- if (stack .isEmpty ()) {
42- return ;
43- }
44-
45- int element = stack .pop ();
46- reverseStack (stack );
47- insertAtBottom (stack , element );
40+ public static void reverseStack (Stack <Integer > stack ) {
41+ if (stack == null ) {
42+ throw new IllegalArgumentException ("Stack cannot be null" );
4843 }
44+ if (stack .isEmpty ()) {
45+ return ;
46+ }
47+
48+ int element = stack .pop ();
49+ reverseStack (stack );
50+ insertAtBottom (stack , element );
51+ }
52+
4953
5054 /**
5155 * Inserts the specified element at the bottom of the stack.
Original file line number Diff line number Diff line change 11package com .thealgorithms .datastructures .stacks ;
22
33import static org .junit .jupiter .api .Assertions .assertEquals ;
4+ import static org .junit .jupiter .api .Assertions .assertThrows ;
45import static org .junit .jupiter .api .Assertions .assertTrue ;
56
67import java .util .Stack ;
78import org .junit .jupiter .api .Test ;
89
910class ReverseStackTest {
1011
12+ @ Test
13+ void testReverseNullStack () {
14+ assertThrows (IllegalArgumentException .class ,
15+ () -> ReverseStack .reverseStack (null ),
16+ "Reversing a null stack should throw an IllegalArgumentException." );
17+ }
18+
19+
1120 @ Test
1221 void testReverseEmptyStack () {
1322 Stack <Integer > stack = new Stack <>();
You can’t perform that action at this time.
0 commit comments