我的输出在不应该打印元素的同时打印 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;
}
最佳答案
您不需要在两端都有虚拟标记。这是因为长度为 n
的 List
的 ListIterator
仅具有 n + 1
个可能的光标位置(在每个位置之前) n
元素的集合,就在最后一个元素
之后)。因此您只需要一个虚拟节点。
我会去掉 endMarker
并将其替换为对最后一个节点的引用。然后,当您调用 l.listIterator(l.size())
时,您将得到一个迭代器,其中 current
最初是最后一个节点,因此您不会得到 null
在迭代开始时。
关于java - ListIterator 类的 Previous() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32983748/