kevorski
kevorski

Reputation: 836

nullpointerexception error removal of node

I'm stuck at this one road and it's really beginning to frustrate me. I think I have everything working properly but this one method.

When I remove a Node from my LL I get a null pointer exception on the next attempt ,and I can't figure out what.

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

It occurs after the removal and restarting of the method. I think it's because I just removed the curr but I'm not 100% sure.

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

Now the current test is that it will remove the second to last node

Upvotes: 0

Views: 1293

Answers (3)

Handol Park
Handol Park

Reputation: 111

Once remove() is called in timeSlice(), curr variable in timeSlice() is pointing to the removed node and curr.getNext() returns null which causes NullPointerException.

As @Catherine suggested, you should keep a reference to the previous node and make its usage cleaner with a dummy node at the head of the list. (Sorry, I don't have enough rep to vote up.)

// 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());
}

Upvotes: 0

Catherine
Catherine

Reputation: 14010

After you call remove on curr, curr's getNext() will return null. Then you go into the next iteration of your loop with a null value for curr.

You should also be checking for null even once you fix that. Why go into the loop if your node is null?

Upvotes: 0

Jayson
Jayson

Reputation: 950

This is probably happening because head == null. Next time post the error stack trace and you'll have a higher chance of getting a more exact answer.

If head is null, you're setting curr to null, then calling the "getNext()" method on null, which will result in a nullPointerException. At least, that's my best guess.

Upvotes: 1

Related Questions