forked from samarthgaur2/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEfficient_Enqueue.java
75 lines (62 loc) · 1.46 KB
/
Efficient_Enqueue.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package Stacks;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by Last on 10/19/2016.
*/
public class Push_Efficient
{
Queue<Integer> q1 = new LinkedList<Integer>(), q2 = new LinkedList<Integer>();
public void push(int data){
q1.add(data);
}
public Integer pop(){
if (q1.isEmpty()){
return Integer.MIN_VALUE;
}
else{
if (q1.size() == 1){
return q1.remove();
}
else{
int size = q1.size();
for (int i = 0; i < size-1; i++) {
q2.add(q1.remove());
}
int x = q1.remove();
q1 = q2;
return x;
}
}
}
public void printStack(){
for (int x:
q1) {
System.out.println(""+x);
}
}
//Driver method
public static void main(String[] args) {
Push_Efficient push_efficient = new Push_Efficient();
push_efficient.push(10);
push_efficient.push(20);
push_efficient.push(30);
push_efficient.push(40);
push_efficient.push(50);
push_efficient.pop();
push_efficient.push(60);
push_efficient.push(70);
push_efficient.pop();
push_efficient.push(80);
push_efficient.printStack();
}
}
//Output
//10
//20
//30
//40
//60
//80