import java.util.Iterator; /** * An Iterator that supports traversing a SimpleLinkedList. * Normally, this would be integrated into the SimpleLinkedList * class by adding the iterator() method to the SimpleLinkedList class: * * @Override * public Iterator iterator() { * return new SimpleLinkedListIterator(this); * } * * Note: this iterator class must be an inner class * within SimpleLinkedList, since it makes use of the private * Node inner class within SimpleLinkedList. * */ public static class SimpleLinkedListIterator implements Iterator { // next node in the traversal private Node nextNode; public SimpleLinkedListIterator(SimpleLinkedList list) { nextNode = list.head; } @Override public boolean hasNext() { return nextNode != null; } @Override public T next() { T val = nextNode.data; nextNode = nextNode.next; return val; } }