doublelylinkedlist的迭代器,如何实现next(),remove()?

时间:2011-08-26 09:45:19

标签: java iterator linked-list

下一个()和删除()我遇到了麻烦。 对于next(),我想返回列表中的下一个元素。 对于remove()从底层集合中删除迭代器返回的最后一个元素(可选操作)。

我理解我想要做的事情,但我在编写代码时遇到了麻烦。有人可以给我一些提示吗?或者向我解释我想要做什么。

这是我的代码,它是一大块混乱。

    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 个答案:

答案 0 :(得分:0)

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