Hi I'm very new to Java and have this problem with building a nested Iterator class for a Doubly Linked List. I wasn't sure how to write a public E next() method to have it iterate through a Doubly-Linked-List.
Any help is greatly appreciated!
  private class DoubleListIterator implements Iterator<E> {
    // instance variable
    private Node current=head;
    private Node last;
    private int index=0;
    public boolean hasNext() {
      return index < N;
    }
    public E next() {
        if (!hasNext()) throw new NoSuchElementException();
    }
    public void remove() { throw new UnsupportedOperationException(); }
  }// end class ListIterator
Try this:
public boolean hasNext() {
  return current != null;
}
public E next() {
    if (!hasNext()) throw new NoSuchElementException();
    E tmp = current.item;
    current = current.next;  // if next is null, hasNext will return false.
    return tmp;
}
Also drop last and index, you dont need them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With