-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRandomizedQueue.java
More file actions
99 lines (81 loc) · 2.13 KB
/
Copy pathRandomizedQueue.java
File metadata and controls
99 lines (81 loc) · 2.13 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import java.util.Iterator;
import java.util.NoSuchElementException;
public class RandomizedQueue<Item> implements Iterable<Item> {
private Item[] a;
private int n;
public RandomizedQueue() {
a = (Item[]) new Object[2];
}
public boolean isEmpty() {
return n == 0;
}
public int size() {
return n;
}
private void resize(int capacity) {
assert capacity >= n;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < n; i++) {
temp[i] = a[i];
}
a = temp;
}
public void enqueue(Item item) {
if (item == null) {
throw new NullPointerException();
}
if (n == a.length) {
resize(2 * a.length);
}
a[n++] = item;
}
public Item dequeue() {
if (isEmpty()) {
throw new NoSuchElementException();
}
StdRandom.shuffle(a, 0, n - 1);
Item item = a[n - 1];
a[n - 1] = null;
n--;
if (n > 0 && n == a.length / 4) {
resize(a.length / 2);
}
return item;
}
public Item sample() {
if (isEmpty()) {
throw new NoSuchElementException();
}
StdRandom.shuffle(a, 0, n - 1);
Item item = a[n - 1];
return item;
}
public Iterator<Item> iterator() {
return new RandomizedQueueIterator();
}
private class RandomizedQueueIterator<Item> implements Iterator<Item> {
private int i = n;
private Item[] r;
public RandomizedQueueIterator() {
r = (Item[]) new Object[n];
for (int j = 0; j < n; j++) {
r[j] = (Item) a[j];
}
StdRandom.shuffle(r);
}
public boolean hasNext() {
return i > 0;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return r[--i];
}
}
public static void main(String[] args) {
}
}