代码出现段错误或从未完成其运行

标签 c linked-list segmentation-fault

我的代码用于从链接列表L中删除值target。由于某种原因我找不到,它要么导致段错误,要么永远不会运行第二个打印语句。如果数字被删除,它也应该返回 0;如果没有,则返回 1。

unsigned int removeNumber(LL_t * L, int target)

{
    int ret = 0;
    node_t * current = L->head;
    node_t * previous = NULL;
    node_t * tmp = current;

    for(current = L->head; current != NULL; previous = current, current->next)
    {
        if ((current->data == target) && (previous != NULL))
        {
            free(current);
            current = current->next;
            previous = current;
            ret += 1;
        }
        else if ((current->data == target) && (previous == NULL)){
            L->head = current->next;
        }
    }
    if (ret > 0)
    {
        return 0;
    }
    return 1;
}

最佳答案

您的代码有一些错误,请改用此代码。

unsigned int removeNumber(LL_t * L, int target)

{
    int ret = 0;
    node_t * current = L->head;
    node_t * previous = NULL;
    node_t * tmp = current;

if(current->data==target)
{
 L->head=current->next;
  free(current);
  ret++;
}

else
{

    for(current = L->head; current->next != NULL; current= current->next)
    {
        if ((current->next->data == target) )
        {
            free(current);
            previous = current->next;
            current->next= previous->next;
            free(previous);
           ret++;
        }

    }

}
   if (ret > 0)
    {
        return 0;
    }
    return 1;
}

关于代码出现段错误或从未完成其运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42882497/

相关文章:

python - python 和 c 信号处理程序如何协同工作?

c - 静态与 Malloc

java - 链表头尾的实用性

c - 从文件读取到链表

c - 带有命令行参数的 Makefile

c - 插入链表 C

c - 使用套接字读取 char* 时出现段错误

c - 第 9 次调用克隆产生段错误

检查空指针在 C 中不起作用(给出段错误)

c - sizeof 函数在外部数组上一直失败