代码如下:
public class LoopListQueue implements Iterable<String> { private NodeStr last; private int n; public boolean isEmpty() { return last == null; } public int size() { return n; } public void enqueue(String item) { NodeStr node = new NodeStr(item); if (isEmpty()) { last = node; node.setNext(node); } else { NodeStr first = last.getNext(); node.setNext(first); last.setNext(node); last = node; } n++; } public String dequeue() { if (isEmpty()) { throw new NoSuchElementException("Queue is empty"); } else { NodeStr first = last.getNext(); last.setNext(first.getNext()); n--; if (n == 0) { last = null; } return first.getItem(); } } private class ListIterator implements Iterator<String> { private NodeStr first = null; private int i = 0; public ListIterator() { if (last != null) { first = last.getNext(); } } @Override public boolean hasNext() { return i < n; } @Override public String next() { String item = first.getItem(); first = first.getNext(); i++; return item; } } @Override public Iterator<String> iterator() { return new LoopListQueue.ListIterator(); } }