【发布时间】:2013-07-09 22:38:44
【问题描述】:
我正在学习 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;
}
【问题讨论】:
-
过去 30 分钟内,这个问题被问了两次。
-
如果您使用 C++ 编译器(例如 Visual C++)编译此代码 - 请检查您的名为
delete的函数是否存在问题。这是一个保留关键字 -
看来
current1这行NULL可能是current2 = current1 -> next; -
我以前在实验室里辅导人的时候,我会让他们在纸上画出他们的链表,然后想象他们的代码在上面运行。这个简单的技巧为他们省去了很多麻烦。
-
粗略一看,我有点怀疑尾部节点上的 'while (current1->next->next != NULL)' 可能会发生什么。
标签: c linked-list segmentation-fault