-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseStack.java
More file actions
45 lines (38 loc) · 944 Bytes
/
ReverseStack.java
File metadata and controls
45 lines (38 loc) · 944 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
45
package learn.ds.stack;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
/**
* @author Varma Penmetsa
*
* https://www.geeksforgeeks.org/reverse-a-stack-using-recursion/
*/
public class ReverseStack {
public static void reverse(Deque<Integer> st) {
if (st.isEmpty()) {
return;
}
int val = st.pop();
reverse(st);
addLast(st, val);
}
public static void addLast(Deque<Integer> st, int val) {
if (st.isEmpty()) {
st.push(val);
} else {
int v = st.pop();
addLast(st, val);
st.push(v);
}
}
public static void main(String[] args) {
Deque<Integer> st = new ArrayDeque<>();
st.push(1);
st.push(2);
st.push(3);
st.push(4);
st.push(5);
reverse(st);
System.out.println(Arrays.toString(st.toArray()));
}
}