2015-05-04 67 views
1

嗨,我对Java很陌生,并且在构建双向链接列表的嵌套迭代器类时遇到此问题。我不确定如何编写一个public E next()方法,让它遍历双链表双重链接列表上的Java迭代器

任何帮助,非常感谢!

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

试试这个:

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,你不需要他们。

+0

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

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

你可能想看看java.util.LinkedList中:

From Documentation

列表和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();