// is the deque empty? publicbooleanisEmpty() { return n == 0; }
// return the number of items on the deque publicintsize() { return n; }
// add the item to the front publicvoidaddFirst(Item item) { if (item == null) thrownew java.lang.NullPointerException(); Node oldfirst = first; first = new Node(); first.item = item; first.next = oldfirst; if (isEmpty()) last = first; else oldfirst.prev = first; n++; }
// add the item to the end publicvoidaddLast(Item item) { if (item == null) thrownew java.lang.NullPointerException(); Node oldlast = last; last = new Node(); last.item = item; last.prev = oldlast; if (isEmpty()) first = last; else oldlast.next = last; n++; }
// remove and return the item from the front public Item removeFirst() { if (isEmpty()) thrownew java.util.NoSuchElementException(); Node oldfirst = first; first = first.next; Item item = oldfirst.item; oldfirst = null; n--; return item; }
// remove and return the item from the end public Item removeLast() { if (isEmpty()) thrownew java.util.NoSuchElementException(); Node oldlast = last; last = last.prev; Item item = oldlast.item; oldlast = null; n--; return item; }
// return an iterator over items in order from front to end public Iterator<Item> iterator() { returnnew ListIterator(); }
publicclassRandomizedQueue<Item> implementsIterable<Item> { privateint n = 0; private Item[] items;
// construct an empty randomized queue publicRandomizedQueue() { items = (Item[]) new Object[2]; }
// is the queue empty? publicbooleanisEmpty() { return n == 0; }
// return the number of items on the queue publicintsize() { return n; }
// add the item publicvoidenqueue(Item item) { if (item == null) thrownew java.lang.NullPointerException(); if (n == items.length) resize(2 * items.length); items[n++] = item; }
// remove and return a random item public Item dequeue() { if (isEmpty()) thrownew java.util.NoSuchElementException();
int index = StdRandom.uniform(n); Item item = items[index]; items[index] = items[n-1]; items[n-1] = null; n--; if (n > 0 && n == items.length/4) resize(items.length/2); return item; }
// return (but do not remove) a random item public Item sample() { if (isEmpty()) thrownew java.util.NoSuchElementException(); int index = StdRandom.uniform(n); return items[index]; }
privatevoidresize(int capacity) { Item[] copy = (Item[]) new Object[capacity]; for (int i = 0; i < n; i++) { copy[i] = items[i]; } items = copy; }
// return an independent iterator over items in random order public Iterator<Item> iterator() { returnnew ListIterator(); }
privateclassListIteratorimplementsIterator<Item> { privateint i = n;
publicclassPermutation{ publicstaticvoidmain(String[] args) { int k = Integer.parseInt(args[0]); RandomizedQueue<String> deque = new RandomizedQueue<String>(); while (!StdIn.isEmpty()) { deque.enqueue(StdIn.readString()); } for (int i = 0; i < k; i++) { StdOut.println(deque.dequeue()); } } }
近期评论