c - 链表清除函数

标签 c pointers linked-list

我正在尝试使用此函数 clearList 清除程序末尾的链接列表,但我不知道该函数的定义究竟有什么问题。

void clearList(struct node *list) { 
    struct node *p; 
    for(p = list; p != NULL; p = p->next)
        free(p);
}

最佳答案

在释放节点之前,您需要获取next 指针:

p = list; //list is the header

while( p != NULL ){
    list = list->next;

    free(p);

    p = list;
}

关于c - 链表清除函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40944515/

相关文章:

编译器相关 - 这两个 C 代码真的相同吗?

c - 迭代存储在堆上的数组

c - libcurl 中的内存泄漏

c++ - 定义函数时不给指针或引用变量命名

Ruby 链表实现 #remove!阻止无效

清除终端程序 Linux C/C++ 的输出

c++ - 多阵列动态内存分配错误

c++ - 指针和 Char 数组问题

c++ - 没有参数的递归,也不是静态或全局变量

c++ - 为 LinkedList 调用 delete 时,变量被分配不同的内存