MCPcopy Create free account
hub / github.com/MolinDeng/Princeton-algs4 / RandomizedQueue

Class RandomizedQueue

02Lab-Queues/RandomizedQueue.java:13–128  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

11import java.util.NoSuchElementException;
12
13public class RandomizedQueue<Item> implements Iterable<Item> {
14 private static final int INIT_CAPACITY = 8;
15 private int n;
16 private Item[] v;
17 private int first;
18 private int last;
19
20 // construct an empty randomized queue
21 public RandomizedQueue() {
22 v = (Item[]) new Object[INIT_CAPACITY];
23 n = 0;
24 first = 0;
25 last = 0;
26 }
27
28 // is the randomized queue empty?
29 public boolean isEmpty() {
30 return n == 0;
31 }
32
33 // return the number of items on the randomized queue
34 public int size() {
35 return n;
36 }
37
38 private void resize(int capacity) {
39 Item[] copy = (Item[]) new Object[capacity];
40 for (int i = 0; i < n; i++)
41 copy[i] = v[(first + i) % v.length];
42 v = copy;
43 first = 0;
44 last = n;
45 }
46
47 // add the item
48 public void enqueue(Item item) {
49 if (item == null) throw new IllegalArgumentException();
50 if (n == v.length) resize(2 * v.length);
51 v[last++] = item;
52 if (last == v.length) last = 0;
53 n++;
54 }
55
56 // remove and return a random item
57 public Item dequeue() {
58 if (isEmpty()) throw new NoSuchElementException();
59 int id = (first + StdRandom.uniformInt(n)) % v.length;
60 Item item = v[id];
61 v[id] = v[first];
62 v[first++] = null;
63 n--;
64 if (first == v.length) first = 0;
65 if (n > 0 && n == v.length / 4) resize(v.length / 2);
66 return item;
67 }
68
69 // return a random item (but do not remove it)
70 public Item sample() {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected