- Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathStackUsingQueuePopEfficient.java
42 lines (33 loc) Β· 757 Bytes
/
StackUsingQueuePopEfficient.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
packagesection11_Queue;
importjava.util.LinkedList;
importjava.util.Queue;
publicclassStackUsingQueuePopEfficient {
Queue<Integer> primary;
Queue<Integer> secondary;
publicStackUsingQueuePopEfficient() {
primary = newLinkedList<Integer>();
secondary = newLinkedList<Integer>();
}
// O(1) Time
publicintpop() {
returnprimary.poll();
}
// O(N) Time
publicvoidpush(intitem) {
secondary.add(item);
while (!primary.isEmpty()) {
secondary.add(primary.poll());
}
// pointing primary queue to secondary queue and vice-versa
Queue<Integer> temp = secondary;
secondary = primary;
primary = temp;
}
// O(1) Time
publicinttop() {
returnprimary.peek();
}
publicintsize() {
returnprimary.size();
}
}