我正在学习 C 中的链表,但我的删除函数有问题,一直给我段错误。我不知道代码有什么问题。
void delete(int d)
{
struct list * current1 = head;
struct list * current2;
if (len() == 0)
{ //prtError("empty");
exit(0);
}
if (head -> data == d)
{
head = head -> next;
}
//Check if last node contains element
while (current1->next->next != NULL)
current1 = current1->next;
if(current1->next->data == d)
current1->next == NULL;
current1 = head; //move current1 back to front */
while(current1 != NULL && (current1->next->data != d))
current1 = current1 -> next;
current2 = current1 -> next;
current1 -> next = current2 -> next;
}
最佳答案
这在很多方面都是错误的:
1)
while (current1->next->next != NULL)
如果列表只有一个元素:
current1 = head;
current1->next = NULL;
current1->next->next = Seg Fault
2)
如果您要查看最后一个元素是否具有提供的数据,请确保在找到它后从函数返回并为其释放内存:
while(current1->next->next != NULL)
current1 = current1->next;
if(current1->next->data == d){
free(current->next);
current1->next == NULL;
return;
}
3)
如果您按照上面的方式搜索,如果最后一个元素包含您的数据(尽管是毫无意义的搜索;无需单独执行),则可以从下面的代码中消除错误情况。但是,当您的数据在列表中找不到并且 current1
位于最后一个元素(因此 != NULL
)但 current1- 时,您仍然会遇到这种情况>next->data != d
使你的程序崩溃。如果您没有从 2) 处的函数返回,就会发生这种情况。
current1 = head; //move current1 back to front */
while(current1 != NULL && (current1->next->data != d))
current1 = current1 -> next;
4)
已删除节点的可用内存:
current2 = current1 -> next;
current1 -> next = current2 -> next;
free(current2);
关于c - 链表分段故障 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17559473/