我已经实现了DoublyLinkedList,如下所示:
public class DoublyLinkedList<E> implements Iterable<E> {
protected static class Node<E> {
private E element;
private Node<E> prev;
private Node<E> next;
public Node(E e, Node<E> p, Node<E> n) {
element = e;
prev = p;
next = n;
}
public void setNext(Node<E> n) {
next = n;
}
}
protected Node<E> header;
protected Node<E> trailer;
private int size = 0;
public DoublyLinkedList() {
header = new Node<>(null, null, null);
trailer = new Node<>(null, header, null);
header.setNext(trailer);
}
现在我正在尝试实现迭代器,这是我提出的解决方案:
private class DLLIterator implements Iterator<E> {
private Node<E> cursor = header;
@Override
public boolean hasNext() {
return cursor != null;
}
@Override
public E next() {
if (!hasNext()) throw new NoSuchElementException("No next element.");
E element = cursor.getElement();
cursor = cursor.getNext();
return element;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Remove not supported.");
}
}
这似乎是正确的,但我对hasNext()方法和初始游标分配有很多疑问。不应该
public boolean hasNext() {
return cursor.getNext() != null;
}
否则,在我看来,迭代器会给我两个null元素,试图从头部和尾部获取它们。我应该改变方法吗?
答案 0 :(得分:0)
@Jorn Vernee的评论包含正确的答案:
更改实现只会使事情复杂化,例如如果 传入的标头为空? hasNext将引发NPE。不会的 因为它检查当前Node是否返回任何null元素 返回之前为null(当然,除非Node包含 空)。