使用链表实现队列(FIFO)。
import static java.lang.System.out; /* 来自 nowjava.com - 时 代 Java*/ import java.util.Iterator; import java.util.NoSuchElementException; public class Queue<Item> implements Iterable<Item> { private Node first, last; private class Node { private Item item; private Node next; } public boolean isEmpty() { return first == null; } public void enqueue(Item item) { Node oldlast = last; last = new Node(); last.item = item;/*n o w j a v a . c o m - 时代Java 提 供*/ last.next = null; if (isEmpty()) first = last; else oldlast.next = last; } public Item dequeue() { Item item = first.item; first = first.next; if (isEmpty()) last = null; return item; } /** * Implements a iterator for Queue, using FIFO. * * <h5>Lecture: Iterators (Week 2)</h5> */ private class QueueIterator implements Iterator<Item> { private Node current = first; public boolean hasNext() { return current != null; } public Item next() { if (!hasNext()) throw new NoSuchElementException(); Item item = current.item; current = current.next; return item; } public void remove() { throw new UnsupportedOperationException(); } } @Override public Iterator<Item> iterator() { return new QueueIterator(); } public static void main(String[] args) { Queue<String> queue =