- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathQueueMin.java
More file actions
Latest commit
51 lines (45 loc) · 1.14 KB
/
Copy pathQueueMin.java
File metadata and controls
51 lines (45 loc) · 1.14 KB
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
packageData_Structures;
importjava.util.*;
publicclassQueueMin<EextendsComparable<? superE>> {
List<E[]> s1 = newArrayList<>();
List<E[]> s2 = newArrayList<>();
Emin(Ea, Eb) {
returna.compareTo(b) < 0 ? a : b;
}
publicEmin() {
if (s1.isEmpty())
returns2.get(s2.size() - 1)[1];
if (s2.isEmpty())
returns1.get(s1.size() - 1)[1];
returnmin(s1.get(s1.size() - 1)[1], s2.get(s2.size() - 1)[1]);
}
publicvoidaddLast(Ex) {
Eminima = x;
if (!s1.isEmpty()) {
minima = min(minima, s1.get(s1.size() - 1)[1]);
}
s1.add((E[]) newComparable[]{x, minima});
}
publicEremoveFirst() {
if (s2.isEmpty()) {
Eminima = null;
while (!s1.isEmpty()) {
Ex = s1.remove(s1.size() - 1)[0];
minima = minima == null ? x : min(minima, x);
s2.add((E[]) newComparable[]{x, minima});
}
}
returns2.remove(s2.size() - 1)[0];
}
// Usage example
publicstaticvoidmain(String[] args) {
QueueMin<Integer> q = newQueueMin<>();
q.addLast(2);
q.addLast(3);
System.out.println(2 == q.min());
q.removeFirst();
System.out.println(3 == q.min());
q.addLast(1);
System.out.println(1 == q.min());
}
}