销毁链表的正确方法? [英] Proper way to destroy linked List?

查看:77
本文介绍了销毁链表的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何彻底销毁我的链表?例如,当我创建链表并调用打印列表功能时,显然没有任何反应,因为列表中什么也没有.当我将节点添加到列表中时,它可以很好地将它们打印出来.但是,当我销毁列表并尝试打印列表时,我希望没有任何内容可以再次打印出来,但是我会断断续续.*我的链接列表的头部也是一个虚拟节点

How do I destroy my linked list completely? For instance, right when I create my linked list and call the print list function, nothing happens obviously since nothing is in the list. When I add nodes to the list, it prints them out fine. But when I destroy my list and try to print the list I expect nothing to print out again, but im seg faulting. *The head of my linked list is a dummy node too

void destroyList(listNode *List)
{
    listNode *temp = malloc(sizeof(listNode));
    temp = List->next;
    while (List != NULL)
    {
        temp = List;
        List = List->next;
        free(temp);             
    }
}

void printList(listNode * List)
{
    List = List->next;

    while (List != NULL)
    {
        printf("%d\n",List->val);        
        List = List->next;     
    }  
}

推荐答案

您之所以遇到段错误,是因为您仍在尝试爬上无法执行的 free 指针的链条.只需将第一个-> next 设置为 NULL ,就可以了.

You're segfaulting because you're still trying to climb down the chain of free'd pointers which you can't do. Just set the first ->next to NULL and you're good to go.

void destroyList(listNode *List)
{
    listNode *temp; // removed malloc, it's not necessary.
    listNode *originalHead = List;
    temp = List->next;
    while (List != NULL)
    {
        temp = List;
        List = List->next;
        free(temp);             
    }

    originalHead->next = NULL;
}

这篇关于销毁链表的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆