The next() and remove() i’m having trouble with.
For the next() i want to return the next element in the list.
For the remove() Removes from the underlying collection the last element returned by the iterator (optional operation).
I understand what i’m suppose to do, but i’m having trouble writing the code. Could someone give me some hints? or explain to me what i’m suppose to do.
Here’s my code, its a big piece of mess.
class DoublyLinkedList12Iterator implements Iterator
{
private Node cursor;
private Node lastNodeReturned;
private Node cursorNext = cursor._next;
private int nextIndex = 0;
// private int prevIndex = -1;
private boolean _hasNextBeenCalled = false;
private int _currentIndex = -1;
//Returns true if the iteration has more elements
public boolean hasNext() {
return _currentIndex < (_size -1);
}
//returns the next element in the iteration
public Object next()
{
_currentIndex++;
_hasNextBeenCalled = true;
/*if(nextIndex == 0)
{
nextIndex++;
return _head._next;
}*/
if(cursor != null)
{
cursor = cursor._next;
}
else
{
throw new NoSuchElementException();
}
//cursor = cursor._next;
lastNodeReturned = cursor;
return cursor._data;
/*prevIndex--;
nextIndex++;
return cursor;
this._prev = this._next;
if(this._next != null);
return the first node
Node cursor = _head;
for(int i = _currentIndex; i < _size ; i++)
{
cursor = cursor._next;
}
return cursor._data;
*/
}
public void remove()
{
if(!_hasNextBeenCalled)
{
throw new IllegalStateException();
}
_hasNextBeenCalled = false;
if(cursor == lastNodeReturned)
{
cursor = cursor._next;
}
else
{
nextIndex--;
}
lastNodeReturned._prev = lastNodeReturned._next;
_size--;
}
}
1 Answer