在更改指针时抛出NullPointerException

时间:2015-10-07 07:24:28

标签: java nullpointerexception linked-list

我必须在LinkedList类中实现undo()方法。每次add()添加任何元素时,该元素都会被推送到undoStack。现在,我有6个元素,代码从这一行抛出NullPointerException

object.prev.next = object.next; 

有人能告诉我如何解决这个问题吗?

protected Node<T> beginMarker;  // Dummy node marking the front of the list
protected Node<T> endMarker;    // Dummy node marking the back of the list

//beginMarker and endMarker are already initialized!

public void undo() {
        if(undoStack.isEmpty()) {
            throw new RuntimeException("Undo history is empty");
        } else {
            Node<T> object = undoStack.topAndPop();
            redoStack.push(object);

            if(object == beginMarker) {
                beginMarker = beginMarker.next;
            } else {
                object.prev.next = object.next; 
            }
            if(object == endMarker) {
                endMarker = object.prev;
            } else {
                object.next.prev = object.prev;
            }
        }
}

0 个答案:

没有答案