-
Notifications
You must be signed in to change notification settings - Fork 0
/
PushAtBottom.java
45 lines (34 loc) · 1.02 KB
/
PushAtBottom.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
package Stacks;
import java.util.*;
public class PushAtBottom {
public static void pushAtBottom(Stack<Integer> stack, int data){
if (stack.isEmpty()){
stack.push(data);
return;
}
// store top values
int top = stack.pop();
// recursion till empty stack and add element
pushAtBottom(stack, data);
// push top elements in the same order
stack.push(top);
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
while(!stack.isEmpty()){
System.out.println("-> " + stack.peek());
stack.pop();
}
System.out.println("\nPush At Bottom");
pushAtBottom(stack, 10);
while(!stack.isEmpty()){
System.out.println("-> " + stack.peek());
stack.pop();
}
}
}