我的输出在不应该打印null的同时显示元素。例如,

        MyList<String> l = new MyList<String>();
        l.add("A");
        l.add("B");
        l.add("C");
        l.add("D");
        l.add("E");
        ListIterator<String> iter = l.listIterator(l.size());
        while(iter.hasPrevious()){
            Object element = iter.previous();
            System.out.print(element + " ");
        }


结果是:

null E D C B A


previous()方法有什么问题,我该如何解决,这样它就不会打印null

protected Node<T> beginMarker;  // Dummy node marking the front of the list
protected Node<T> endMarker;    // Dummy node marking the back of the list
....................
public class AListIterator implements ListIterator<T>{
        protected Node<T> current;
        protected Node<T> lastVisited = null;
        protected int expectedModCount = modCount;
public boolean hasPrevious( ){
            if( expectedModCount != modCount )
                throw new ConcurrentModificationException( );

            return current != beginMarker;
        }

public T previous( ){
            if( expectedModCount != modCount )
                throw new ConcurrentModificationException( );
            if(!hasPrevious( ))
                throw new RuntimeException("Already at beginning of list");

            T prevItem = current.data;
            current = current.prev;
            return prevItem;
        }

最佳答案

您不需要两端都使用虚拟标记。这是因为长度为ListIteratorListn仅具有n + 1可能的光标位置(在每个n元素之前,并且在最后一个element之后)。因此,您只需要一个虚拟节点。

我将摆脱endMarker并将其替换为对最后一个节点的引用。然后,当您调用l.listIterator(l.size())时,将得到一个迭代器,其中current最初是最后一个节点,因此在迭代开始时将不会得到null

09-30 15:06
查看更多