forked from vishal8113/Hacktoberfest-2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseStack.java
41 lines (34 loc) · 858 Bytes
/
ReverseStack.java
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
//Problem Statement -
// Given a stack, you need to reverse it and print its elements.
import java.util.Stack;
public class ReverseStack {
public static void addAtBottom(int data, Stack<Integer> s) {
if(s.empty()) {
s.push(data);
return;
}
int top = s.pop();
addAtBottom(data, s);
s.push(top);
}
public static void reverse(Stack<Integer> s) {
if(s.empty()) {
return;
}
int top = s.pop();
reverse(s);
addAtBottom(top, s);
}
public static void main(String[] args) {
Stack<Integer> s = new Stack<>();
s.push(0);
s.push(1);
s.push(2);
s.push(3);
reverse(s);
while (!s.empty()) {
System.out.print(s.peek() + " ");
s.pop();
}
}
}