首页 > 解决方案 > 如何删除整个列表,而不仅仅是删除列表中的元素?

问题描述

这是我必须在列表中创建列表和元素的代码。现在我想实现一个函数来删除整个列表,而不仅仅是清空列表。我怎么做?

struct node
{
    int number;        
    struct node* next; 
};

struct forward_list
{
    struct node* head;
};

typedef struct node node;

node* create_node(int number, node* next)
{
    node* result = (node*)malloc(sizeof(node));
    result->number = number;
    result->next = next;
    return result;
}


//edit
void destroy_node(node* const this)
{
    free(this);
}
void destroy_list(forward_list* const this)
{
    /* TODO */
}

标签: c

解决方案


看到你的编辑,我认为你只需要destroy_node迭代地调用destroy_list来清空你的列表,从而破坏它。

[编辑]

我不得不将列表的头部设置NULL在最后。感谢您的评论!

像这样的东西:

void destroy_list(forward_list* const this)
{
    node* temp = this->head;
    node* to_delete;

    while(temp != NULL){
      to_delete = temp;
      temp = temp->next;
      destroy_node(to_delete);
    }
    this->head = NULL;

}

推荐阅读