Java双向链表上的迭代器

3

你好,我对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
3个回答

4

试试这个:

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

另外去掉lastindex,因为你不需要它们。

顺便提一下,我的解决方案中字段名current不正确。如果您接受我的解决方案,请将其重命名为nextcursor之类的名称。 - Grim

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

0
你可能想看一下 java.util.LinkedList: 来自文档
List 和 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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接