Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm not sure how to go about utilizing the given position(x) that won't affect my ListIterator constructor which starts at head.

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.

Edit:

public ListIterator()
        {
            current = head; // head in the enclosing list
        }
like image 984
user3769402 Avatar asked Dec 02 '22 17:12

user3769402


1 Answers

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

Otherwise, you could traverse the list to the xth node, but there's no reason you can't do it this way.

like image 171
Radiodef Avatar answered Dec 23 '22 19:12

Radiodef