Click to See Complete Forum and Search --> : Delete Nodes


HypnotiC
October 27th, 2004, 12:53 PM
Hi...

I have a singly linked list, I want to delete all nodes that have the value (number).
I got this code but i doesnt work. i dont know
please anyone can tell me what's the wrong or write me the write method ?


public void delete( int number )
{
MyNode node = head;
while( node.getNext() != null ) {
MyNode temp = node;
node = node.getNext();

while( node.getNumber() == number ) {
temp.setNext( node.getNext() );
node = temp.getNext();
}
}
}

HypnotiC
October 27th, 2004, 12:54 PM
Sorry ... the right method not the ( write method )

Thanks .....

mehdi62b
October 28th, 2004, 08:16 AM
Hi HypnotiC,
I changed your code,try this and tell me whether it works or not.

public void delete( int number )
{
MyNode node = head;
while( node.getNext() != null ) {
MyNode temp = node;
node = node.getNext();

if( node.getNumber() == number ) {
temp.setNext( node.getNext() );
node = temp;
}
}
}

HtH.

HypnotiC
October 28th, 2004, 10:56 AM
Hello...

Thanks friend .. Ok it works as required but there is NullPointerException
appears .. what might this be ?

MrViggy
October 28th, 2004, 11:08 AM
First, it doesn't look like the very first node is checked for the number in question. Second, the null pointer exception is happening because inside the loop, you are setting 'node' to the next node, then immediately trying to dereference it. When you get to the last node in the list, you'll get a null pointer exception (assuming the last node points to NULL).

Viggy