Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Iterator on Doubly-linked-list

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
like image 254
Robert Avatar asked Oct 28 '25 09:10

Robert


1 Answers

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.

like image 133
Grim Avatar answered Oct 29 '25 23:10

Grim