/ / iteratory dla podwójnie dowiązanej listy, jak zaimplementować next (), remove ()? - java, iterator, lista linków

iteratory dla podwójnie linkowanej listy, jak zaimplementować next (), remove ()? - java, iterator, lista linków

Następna () i remove () mam problem. Dla next () chcę zwrócić następny element na liście. Dla remove () Usuwa z podstawowej kolekcji ostatni element zwracany przez iterator (operacja opcjonalna).

Rozumiem, co powinienem zrobić, ale mam problem z napisaniem kodu. Czy ktoś mógłby mi dać jakieś wskazówki? lub wyjaśnij mi, co mam zrobić.

Oto mój kod, to duży bałagan.

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



}

}

Odpowiedzi:

0 dla odpowiedzi № 1
public T next() {
if (nextnode == null)
throw new NoSuchElementException();
currentnode = nextnode;
previousnode = currentnode.previous;
nextnode = currentnode.next;
return currentnode.element;
}

public void remove() {
if (previousnode != null)
previousnode.next = nextnode;
if (nextnode != null)
nextnode.previous = previousnode;
}