c - 链表分段故障 C

标签 c linked-list segmentation-fault

我正在学习 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/

相关文章:

c - 为什么我的代码中出现段错误,您能解释一下按引用传递和按值传递吗?

c - 如何解决函数之间的循环依赖?

c - 从 C 文件中读取标记

c++ - 什么是符号表?

c - 在c中构建链接列表时出错

c - 分离链表中的偶数和奇数节点

c++ - 令人抓狂的链表问题

c - 锁定顺序或调度问题

java - Java 中 LinkedList 的迭代器时间复杂度?

c++ - Boost图分割错误