File tree Expand file tree Collapse file tree 2 files changed +21
-8
lines changed
main/java/com/thealgorithms/datastructures/stacks
test/java/com/thealgorithms/datastructures/stacks Expand file tree Collapse file tree 2 files changed +21
-8
lines changed Original file line number Diff line number Diff line change @@ -37,15 +37,19 @@ private ReverseStack() {
37
37
*
38
38
* @param stack the stack to reverse; should not be null
39
39
*/
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" );
48
43
}
44
+ if (stack .isEmpty ()) {
45
+ return ;
46
+ }
47
+
48
+ int element = stack .pop ();
49
+ reverseStack (stack );
50
+ insertAtBottom (stack , element );
51
+ }
52
+
49
53
50
54
/**
51
55
* Inserts the specified element at the bottom of the stack.
Original file line number Diff line number Diff line change 1
1
package com .thealgorithms .datastructures .stacks ;
2
2
3
3
import static org .junit .jupiter .api .Assertions .assertEquals ;
4
+ import static org .junit .jupiter .api .Assertions .assertThrows ;
4
5
import static org .junit .jupiter .api .Assertions .assertTrue ;
5
6
6
7
import java .util .Stack ;
7
8
import org .junit .jupiter .api .Test ;
8
9
9
10
class ReverseStackTest {
10
11
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
+
11
20
@ Test
12
21
void testReverseEmptyStack () {
13
22
Stack <Integer > stack = new Stack <>();
You can’t perform that action at this time.
0 commit comments