Skip to content

Instantly share code, notes, and snippets.

@wyukawa
Created March 29, 2019 02:23
Show Gist options
  • Save wyukawa/a40295ca54cca36fecbe47be0d8a657d to your computer and use it in GitHub Desktop.
Save wyukawa/a40295ca54cca36fecbe47be0d8a657d to your computer and use it in GitHub Desktop.
import edu.princeton.cs.algs4.StdRandom;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class RandomizedQueue<Item> implements Iterable<Item> {
private Item[] items;
private int index = 0;
public RandomizedQueue() {
items = (Item[]) new Object[10];
}
public boolean isEmpty() {
return index == 0;
}
public int size() {
return index;
}
public void enqueue(Item item) {
if (item == null) {
throw new IllegalArgumentException();
}
if (index == items.length) {
resize(2 * items.length);
}
items[index++] = item;
}
private void resize(int capacity) {
Item[] copy = (Item[]) new Object[capacity];
for (int i = 0; i < index; i++) {
copy[i] = items[i];
}
items = copy;
}
public Item dequeue() {
if (isEmpty()) {
throw new NoSuchElementException();
}
int i = StdRandom.uniform(0, size());
Item item = items[i];
items[i] = null;
index--;
return item;
}
public Item sample() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return items[StdRandom.uniform(0, size())];
}
public Iterator<Item> iterator() {
return new RandomizedQueueIterator();
}
private class RandomizedQueueIterator implements Iterator<Item> {
@Override
public boolean hasNext() {
return !isEmpty();
}
@Override
public Item next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return dequeue();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment