双向链表上的 Java 迭代器

Rob*_*ert 4 java iterator doubly-linked-list

您好,我对 Java 很陌生,在为双向链表构建嵌套 Iterator 类时遇到了这个问题。我不确定如何编写一个public E next()方法来让它迭代双向链表

任何帮助是极大的赞赏!

  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
Run Code Online (Sandbox Code Playgroud)

Pet*_*der 5

尝试这个:

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;
}
Run Code Online (Sandbox Code Playgroud)

也放下lastindex,你不需要它们。