| 10 | import java.util.NoSuchElementException; |
| 11 | |
| 12 | public class LinkedRandomizedQueue<Item> implements Iterable<Item> { |
| 13 | private class Node { |
| 14 | Item item; |
| 15 | Node next; |
| 16 | } |
| 17 | |
| 18 | private Node first; |
| 19 | private Node last; |
| 20 | private int n; |
| 21 | |
| 22 | // construct an empty randomized queue |
| 23 | public LinkedRandomizedQueue() { |
| 24 | first = null; |
| 25 | last = null; |
| 26 | n = 0; |
| 27 | } |
| 28 | |
| 29 | // is the randomized queue empty? |
| 30 | public boolean isEmpty() { |
| 31 | return n == 0; |
| 32 | } |
| 33 | |
| 34 | // return the number of items on the randomized queue |
| 35 | public int size() { |
| 36 | return n; |
| 37 | } |
| 38 | |
| 39 | // add the item |
| 40 | public void enqueue(Item item) { |
| 41 | if (item == null) throw new IllegalArgumentException(); |
| 42 | Node oldLast = last; |
| 43 | last = new Node(); |
| 44 | last.item = item; |
| 45 | last.next = null; |
| 46 | if (isEmpty()) first = last; |
| 47 | else oldLast.next = last; |
| 48 | n++; |
| 49 | } |
| 50 | |
| 51 | // remove and return a random item |
| 52 | public Item dequeue() { |
| 53 | if (isEmpty()) throw new NoSuchElementException(); |
| 54 | int cnt = StdRandom.uniformInt(n); |
| 55 | Node p = first; |
| 56 | Node prevP = null; |
| 57 | while (cnt-- > 0) { |
| 58 | prevP = p; |
| 59 | p = p.next; |
| 60 | } |
| 61 | Item item = p.item; |
| 62 | n--; |
| 63 | if (prevP == null) first = p.next; |
| 64 | else prevP.next = p.next; |
| 65 | if (p == last) last = prevP; |
| 66 | return item; |
| 67 | } |
| 68 | |
| 69 | // return a random item (but do not remove it) |
nothing calls this directly
no outgoing calls
no test coverage detected