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