C语言 代码给出分段错误或从未完成其运行



我的代码用于从链表中删除值target L .由于某种原因我找不到,它要么导致分段错误,要么永远不会运行第二个打印语句。如果删除数字,它还应返回 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;
}

相关内容

  • 没有找到相关文章