我正在学习C语言中的链表,我的删除功能有问题。线路出现分段故障:while(current1 != NULL && (current1->next->data != d))
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;
}
最佳答案
您的测试要确保current1
中至少有一个元素,因此current1 != NULL
可以保证工作,但它可能返回current1->next
本身,导致NULL
在尝试从下一个元素获取数据时崩溃。
关于c - C结构链表分割错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17559120/