简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM