c - 从链表中删除节点(C)

标签 c data-structures linked-list

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;
    }
}
}

程序在必须遍历链表时崩溃,我认为这与指针ptr和prev有关。我的逻辑是遍历列表,直到 ptr 遇到包含目标数据的节点。一旦它跳出循环并使 prev 指向 ptr->next 指向的节点。

最佳答案

如果目标数据不在根节点上,则转到第一个 while 迭代,然后使用 prev->next = ptr; 到达 else但 prev 仍然是 NULL ---> 程序崩溃。

只需使用调试器 - 您会很快发现此错误。

关于c - 从链表中删除节点(C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44098945/

相关文章:

C 程序 - 执行 - while 循环不起作用

c - 警告 : parameter names (without types) in function declaration [enabled by default]

python - 检查二叉树是否对称的技术

c++ - 链表数据访问

c++ - C 链表 - 不允许指向不完整类的指针

c++ - 为什么 MPI_Scatterv 的 recvcount 是一个固定的 int 而 sendcount 是一个数组?

C语言函数错误

java - 如何存储数据结构匹配.proto

python - 可散列的,不可变的

c - 程序中的未知错误