编程语言
首页 > 编程语言> > Java Iterator双链表

Java Iterator双链表

作者:互联网

嗨,我对Java很新,并尝试通过实现双链表格式来创建Deque类.当我运行代码(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;}
            }

解决方法:

我做了两处改动.

>正如图库西已经说过,增量指数.
>从头开始电流,而不是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();
}
}

标签:deque,doubly-linked-list,java,nullpointerexception
来源: https://codeday.me/bug/20190829/1764086.html