aDabOfRanch aDabOfRanch -4 years ago 75
C Question

Deleting Nodes from a Linked List (C)

void delete()
{
if(root == NULL)
{
printf("ERROR EMPTY LIST.\n");
}
else
{
printf("Enter value: ");
scanf("%d",&target);

if(root->data == target)
{
root = root->next;

}
else
{
struct node *ptr = root;
struct node *prev = NULL;

while(ptr != NULL)
{
if(ptr->data == target)
{
break;
}else
{
prev->next = ptr;
ptr = ptr->next;
}
}

prev->next = ptr->next;
}
}
}


The program crashes when it has to to traverse the linked list, and I think it has something to do with the pointers ptr and prev. My logic is traverse the list until ptr runs into a node that contains the target data. Once it does break out of the loop and make prev point to the node ptr->next points to.

Answer Source

If the target data is not on the root node, you go to the first while iteration, and then you reach the else with prev->next = ptr; but prev is still NULL ---> program crashes.

Just use a debugger - you'd find this bug really fast.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download