双链表上的Java迭代器

双链表上的Java迭代器,java,iterator,doubly-linked-list,Java,Iterator,Doubly Linked List,您好,我是Java新手,在为双链表构建嵌套迭代器类时遇到了这个问题。我不知道如何编写一个public E next()方法,让它在双链接列表中迭代 非常感谢您的帮助 private class DoubleListIterator implements Iterator<E> { // instance variable private Node current=head; private Node last; private int index=

您好,我是Java新手,在为双链表构建嵌套迭代器类时遇到了这个问题。我不知道如何编写一个
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
私有类DoubleListIterator实现迭代器{
//实例变量
私有节点电流=头;
最后是私有节点;
私有整数指数=0;
公共布尔hasNext(){
回归指数
试试这个:

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;
}

也可以删除
last
index
,您不需要它们。

您可能需要查看java.util.LinkedList:

 public E next() {
        if (!hasNext()) throw new NoSuchElementException();
             current = current.next;
    return current;
    }
:

列表和Deque接口的双链表实现。实现所有可选的列表操作,并允许所有元素(包括null)。 所有操作的执行都与双链接列表的预期一样。索引到列表中的操作将从开始或结束遍历列表,以更接近指定索引的为准

LinkedList<String> linkedlist = new LinkedList<String>();

     //add(String Element) is used for adding

     linkedlist.add("Item1");
     linkedlist.add("Item5");
     linkedlist.add("Item3");

      /*Add First and Last Element*/

     linkedlist.addFirst("First Item");
     linkedlist.addLast("Last Item");

     //you can get the iterator by 
     ListIterator<String> it = linkedlist.listIterator();
LinkedList LinkedList=新建LinkedList();
//add(String元素)用于添加
linkedlist.add(“第1项”);
linkedlist.add(“第5项”);
linkedlist.add(“第3项”);
/*添加第一个和最后一个元素*/
linkedlist.addFirst(“第一项”);
linkedlist.addLast(“最后一项”);
//您可以通过以下方式获得迭代器:
ListIterator it=linkedlist.ListIterator();

顺便说一下,在我的解决方案中,字段名
current
不正确。如果您接受我的解决方案,请将其重命名为
next
cursor