-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reverse_Stack.java
54 lines (40 loc) · 1.16 KB
/
Reverse_Stack.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
42
43
44
45
46
47
48
49
50
51
52
53
54
package Stacks;
import java.util.*;
public class Reverse_Stack {
public static void pushAtBottom(Stack<Integer> stack, int data){
if (stack.isEmpty()) {
stack.push(data);
return;
}
int top = stack.pop();
pushAtBottom(stack, data);
stack.push(top);
}
public static void reverseStack(Stack<Integer> stack){
if (stack.isEmpty()) return;
int top = stack.pop();
reverseStack(stack);
pushAtBottom(stack, top);
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
while (!stack.isEmpty()){
System.out.println("-> "+ stack.peek());
stack.pop();
}
System.out.println("\nReverse Stack");
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
reverseStack(stack);
while (!stack.isEmpty()){
System.out.println("-> "+ stack.peek());
stack.pop();
}
}
}