-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPushBottom.java
More file actions
41 lines (35 loc) · 908 Bytes
/
Copy pathPushBottom.java
File metadata and controls
41 lines (35 loc) · 908 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
import java.util.*;
public class PushBottom {
public static void pushBottom(Stack <Integer> s,int target){
Stack <Integer> st = new Stack<>();
while(!s.isEmpty()){
st.push(s.pop());
}
s.push(target);
while(!st.isEmpty()){
s.push(st.pop());
}
}
public static void pushBottomOptimised(Stack <Integer> s , int data){
if(s.isEmpty()){
s.push(data);
return;
}
int top = s.pop();
pushBottom(s, data);
s.push(top);
}
public static void main(String args[]){
Stack <Integer> s = new Stack<>();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
//pushBottom(s, 0);
pushBottomOptimised(s, 5);
while(!s.isEmpty()){
System.out.println(s.peek());
s.pop();
}
}
}