0

我被困在这条路上,它真的开始让我感到沮丧。我认为除了这一种方法外,我的一切工作正常。

当我从我的 LL 中删除一个节点时,我在下一次尝试时得到一个空指针异常,我不知道是什么。

public void timeSlice(int cpuTime){
    for(Node curr=head; curr.getNext()!=head; curr=curr.getNext()){
        curr.time=curr.time-cpuTime;
        System.out.print("<" + curr.pid + ", " + curr.time +">" + " ");
        //if the time remaining <= 0 then remove the node
        if(curr.time<=0){
            System.out.println("\nProcess " + curr.pid + " has finished, and is now being terminated");
            remove(curr);
        }
    }
}//end timeSlice

它发生在删除并重新启动该方法之后。我认为这是因为我刚刚删除了 curr,但我不是 100% 确定。

public void remove(Node node){
    if(size == 0){
        return; 
    }
    else if(size == 1){
        removeFirst();
    }
    else{
        Node curr;
        for(curr=head; curr.getNext()!=node; curr=curr.getNext()){
        ;
        }
        curr.setNext(curr.getNext().getNext());
        node.setNext(null);
    }
        size --;
}//end remove

现在当前的测试是它将删除倒数第二个节点

4

3 回答 3

1

这可能是因为 head == null 而发生的。下次发布错误堆栈跟踪,您将有更高的机会获得更准确的答案。

如果 head 为 null,则将 curr 设置为 null,然后在 null 上调用“getNext()”方法,这将导致 nullPointerException。至少,这是我最好的猜测。

于 2013-04-22T02:22:32.500 回答
0

一旦remove()被调用timeSlice()curr变量 intimeSlice()将指向被移除的节点并curr.getNext()返回nullwhich cause NullPointerException

正如@Catherine 建议的那样,您应该保留对前一个节点的引用,并在列表的头部使用一个虚拟节点来使其使用更清晰。(对不起,我没有足够的代表来投票。)

// head.getNext() == head
Node head = new Node();

public void timeSlice(int cpuTime) {
    Node prev = head; // A dummy at head.
    Node curr = prev.getNext();
    for ( ; curr != head; prev = curr, curr = curr.getNext()) {
        // ...
        if (/* remove? */) {
            removeNext(prev);
            curr = prev;
        }
    }
}

public void removeNext(Node node) {
    node.setNext(node.getNext().getNext());
}
于 2013-04-22T02:37:23.003 回答
0

在你打电话后removecurr' currsgetNext()会回来的null。然后你进入循环的下一次迭代,null值为curr.

null即使您修复了该问题,您也应该进行检查。如果您的节点为空,为什么要进入循环?

于 2013-04-22T02:38:03.947 回答