如何让List Iterator从给定索引开始? [英] How to have List Iterator start at a given index?

查看:48
本文介绍了如何让List Iterator从给定索引开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个链表,我需要使方法在列表中的给定点返回迭代器.我目前有一个从头开始的迭代器:

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.

这篇关于如何让List Iterator从给定索引开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆