forked from avinashbest/java-coding-ninjas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseStack.java
More file actions
44 lines (32 loc) · 948 Bytes
/
Copy pathReverseStack.java
File metadata and controls
44 lines (32 loc) · 948 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package stacks;
import java.util.Stack;
public class ReverseStack {
public static void main(String[] args) {
int[] arr = {5, 6, 7, 1, 9};
Stack<Integer> stack = new Stack<>();
Stack<Integer> helper = new Stack<>();
for (int element : arr) {
stack.push(element);
}
reverseStack(stack, helper);
while (!stack.empty()) {
System.out.println(stack.pop());
}
}
private static void reverseStack(Stack<Integer> stack, Stack<Integer> helper) {
if (stack.size() <= 1) {
return;
}
int lastElement = stack.pop();
reverseStack(stack, helper);
while (!stack.isEmpty()) {
int top = stack.pop();
helper.push(top);
}
stack.push(lastElement);
while (!helper.isEmpty()) {
int top = helper.pop();
stack.push(top);
}
}
}