Java 迭代器双向链表

Java Iterator Doubly Linked list

您好,我是 Java 的新手,正在尝试通过实现双向链表格式来创建 Deque class。当我 运行 代码 (DequeApp) 时,我得到一个 NullPointerException 引用回我的 Iterator.next(Deque.java:44).

Error messages:  **Exception in thread "main" java.lang.NullPointerException
    at dlist.Deque$DoubleListIterator.next(Deque.java:44)



        public E next() {
                if (!hasNext()) {throw new NoSuchElementException();}
                else{
                E temp = current.item;
                current = current.next;
                return temp;}
            }

您忘记在 DoubleListIterator 中递增 index 计数器。你写:

public E next() {
    if (!hasNext()) {
        throw new NoSuchElementException();
    } else {
        E temp = current.item;
        current = current.next;
        return temp;
    }
}

你应该写:

public E next() {
    if (!hasNext()) {
        throw new NoSuchElementException();
    } else {
        index ++; // <---- without this, hasNext() always returns true
        E temp = current.item;
        current = current.next;
        return temp;
    }
}

另请注意,我已将缩进格式更改为 Oracle 指南的格式。

第二个错误是您按如下方式初始化迭代器:

    private Node current=head.next;

但是,这使得无法检索 head(因为您已经指向其 next 节点)。它使您的索引计数器减一。更正后的代码:

    private Node current=head;

我做了两处修改。

  1. tucuxi已经说过了,增加索引。
  2. 从头部开始电流,而不是head.next。

    private class DoubleListIterator implements Iterator<E> {
    // instance variable
    private Node current = head;
    private int index = 0;
    
    public boolean hasNext() {
        return index < N;
    }
    
    public E next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        } else {
            index++;
            E temp = current.item;
            current = current.next;
            return temp;
        }
    }
    
    public void remove() {
        throw new UnsupportedOperationException();
    }
    }
    

另一个使用索引变量的选项是

也许你可以在 hasNext 中尝试 "current.next != null"。

但如果它已经在使用索引,那么就没有问题。