如何让列表迭代器从给定的索引开始? [英] How to have List Iterator start at a given index?
问题描述
我有一个链表,我需要在列表中的给定点创建一个返回迭代器的方法.我目前有一个从头开始的迭代器:
I have a linked list and I need to make method that returns an iterator at a given point in the list. I currently have an iterator that starts at the head:
public Iterator<E> iterator( )
{
return new ListIterator();
}
我对另一个的唯一要求是:
All I have for the other one is:
public Iterator<E> iterator(int x )
{
return new ListIterator();
}
我不知道如何利用给定的 position(x) 不会影响我从头开始的 ListIterator 构造函数.
I'm not sure how to go about utilizing the given position(x) that won't affect my ListIterator constructor which starts at head.
我尝试使用 for 循环到达x",但意识到这不会告诉迭代器从那里开始,所以我很困惑.
I tried using a for loop to get to "x" but realized that wouldn't tell the iterator to start there, so I'm quite stumped.
public ListIterator()
{
current = head; // head in the enclosing list
}
推荐答案
在没有看到你的实现的情况下,最简单的方法是:
Without seeing your implementation, the trivial way to do this is:
public Iterator<E> iterator(int x) {
if (x < 0 || this.size() < x) {
throw new IndexOutOfBoundsException();
}
Iterator<E> it = new ListIterator();
for (; x > 0; --x) {
it.next(); // ignore the first x values
}
return it;
}
否则,您可以将列表遍历到第 x 个节点,但没有理由不能这样做.
Otherwise, you could traverse the list to the xth node, but there's no reason you can't do it this way.
这篇关于如何让列表迭代器从给定的索引开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!