title | date | draft | tags | categories | |||
---|---|---|---|---|---|---|---|
Algorithm4 Java Solution 1.3.35 |
2019-07-04 05:47:10 +0800 |
false |
|
|
Random queue. A random queue stores a collection of items and supports the following API:
Write a class RandomQueue that implements this API. Hint : Use an array representation (with resizing). To remove an item, swap one at a random position (indexed 0 through N-1) with the one at the last position (index N-1). Then delete and return the last object, as in ResizingArrayStack. Write a client that deals bridge hands (13 cards each) using RandomQueue.
public Item dequeue() {
if (isEmpty()) {
return null;
}
if (N > 0 && N == a.length / 4) {
resize(a.length / 2);
}
int r = StdRandom.uniform(N);
Item item = a[r];
// delete
a[r] = a[N - 1];
a[N - 1] = null;
N--;
return item;
}