0

我正在制作遍历节点列表的迭代器方法(迭代器(int index)。这个特定的方法将返回一个迭代器,该迭代器的行为方式首先调用方法 next() 将给出索引参数的值。这是我第一次使用迭代器,因此感谢您的帮助!

  private class DoublelinkedlistIterator implements Iterator<T>
  {
    private Node<T> p;
    private boolean removeOK;


    private DoublelinkedlistIterator()
    {
      p = head;         // p is first in the list
     removeOK = false;  

    }

    public boolean hasNext()
    {

        if(p.neste != null )
        {
            return true;
        }

        return false;
    }

    public T next()
    {

      Node<T> q = p;

      p = p.next; // go to next
      removeOK = true;
      return q.value; // return current value


    }

    public void remove() // in the making
    {

     removeOK = false;
    }

  } // class DoublelinkedlistIterator

  public Iterator<T> iterator()
  {
    return new DoublelinkedlistIterator();
  }

  public Iterator<T> iterator(int index) // its this one I need help with
  {


     next();
  }
4

1 回答 1

0

您应该简单地创建迭代器并调用 next 直到您处于正确的索引处:

public Iterator<T> iterator(int index) {
    Iterator<T> it = new DoublelinkedlistIterator();
    for (int i = 0; i < index && it.hasNext(); i++, it.next());
    return it;
}

请注意,如果index大于列表的长度,则迭代器将不会指向任何元素,而是处于hasNext()返回的状态false

于 2013-10-20T18:19:03.990 回答