Reputation: 3409
I have this function deleteNode()
for deleting a node from a linked list. This func. is called in the main func. like this deleteNode(&head, 10);
, where head
is the pointer to the first node of the linked list and 10
the value to be deleted.
Here, the else if
statement is commented and the function runs fine. But when I uncomment the else if
statement and run then the program crashes. Why is it happening and what is the solution?
void deleteNode(node **h, int value)
{
node *current, *temp;
current = *h;
while(current != NULL)
{
// if the node to be deleted is the first node of the list
if(current == *h && current->data == value)
{
*h = current->next;
}
/*
// if the node to be deleted is other than first node
else if(current->next->data == value)
{
temp = current->next;
current->next = temp->next;
free(temp);
} */
current = current->next;
}
}
Upvotes: 1
Views: 75
Reputation: 282120
In your code you are trying to delete a single node from linked list with a given value, but since you are continuing the loop it will delete all the nodes with the given value after you fix the bug i.e. checking current->next != NULL before checking its data. You could refer to the following code to delete a single node.
void deleteNode(node **h, int value)
{
node *current, *temp;
current = *h;
while(current != NULL)
{
// if the node to be deleted is the first node of the list
if(current == *h && current->data == value)
{
*h = current->next;
free(current);
return;
}
// if the node to be deleted is other than first node
else if(current->next != NULL && current->next->data == value)
{
temp = current->next;
current->next = temp->next;
free(temp);
return;
}
current = current->next;
}
}
Upvotes: 1
Reputation: 7479
Because you're trying to access current->next->data
without checking if the current->next
is null first. You should modify your logic either to check if current->next != null
before trying to access its data, or to check the current->data
and remove it by saving the previous
node also.
Upvotes: 1