【问题标题】:Using a function to free a linked list with double pointer使用函数释放带有双指针的链表
【发布时间】:2016-10-12 18:45:04
【问题描述】:

我很难删除单个函数中链接中的所有成员。如果我像您在下面看到的那样分解它,它可以正常工作,但这似乎非常低效,并且想要找出正确的方法来做到这一点。为了释放所有节点,我需要先释放除头部以外的所有节点,然后释放头部链接的功能。这似乎很容易做到,但我遇到了麻烦。

感谢您的帮助!

int main() {

    struct node *head = NULL;
    createList(&head);

    //do stuff with list

    freeListMembers(head);
    freeListHead(&head);

    return 0;
}

int createList(struct node **head) {
    //create list
    return 0;
}

void freeListMembers(struct node *head){
    while(head->next != NULL){
        head->next = NULL;
        free(head->next);  
    }
    return;  
}

void freeListHead(struct node **head) {
    *head = NULL;
    free(*head); 
    return;
}

这是我想工作但没有工作的代码。我看到的问题是“*head->next;”的错误它说“表达式必须具有指向结构或联合类型的指针”

int main() {

    struct node *head = NULL;
    createList(&head);

    //do stuff with list

    freeAllListMembers(&head);

    return 0;
}

int createList(struct node **head) {
    //create list
    return 0;
}

void freeAllListMembers(struct node **head){ 
    while (head != NULL) {
        struct node *temp = *head->next;
        free(*head);
        *head = temp ;
    }
   return;  
}

【问题讨论】:

  • 确实有一个释放头部和所有成员的功能。它被命名为main()。如果您提出您尝试过的东西,因此您的问题会更清晰,并且会为答案提供更多吸引力,因此具有您想要的形式,但这对您不起作用。
  • @JohnBollinger 谢谢!我在上面添加了我想要工作的代码

标签: c function linked-list free double-pointer


【解决方案1】:

来自您的代码:

void freeListMembers(struct node *head){
    while(head->next != NULL){
        head->next = NULL;
        free(head->next);  
    }
    return;  
}

这是释放 NULL,而不是你的节点*。

释放列表就像使用指向下一个节点的临时指针一样简单。

while (head) {
    node* next = head->next;
    free(head);
    head = next;
}

来自您的编辑:

void freeAllListMembers(struct node **head){ 
    while (head != NULL) {
        struct node *temp = *head->next;
        free(*head);
        *head = temp ;
    }
   return;  
}

这有几个错误。它应该是while (*head != NULL)(*head)->next。第一个是逻辑错误,因为 head 总是非 NULL,第二个是语法错误,因为在访问下一个指针之前需要取消对 head 指针的引用。

【讨论】:

  • 感谢@MarcD,我最初尝试了您的建议,但这不起作用,我将代码添加到上面的线程中并提供更多信息
  • 我编辑了我的答案,向您展示您尝试的代码有什么问题。
  • 这成功了!谢谢, (head != NULL) 只是一个错字,但 (*head)->next 是我缺少的部分,为什么需要括号?这到底是在做什么?我也在考虑设置 *head = NULL;在空闲(*头)之前;。我读到最好在释放指针之前将指针设置为 null,这对我的情况也正确吗?
  • 在释放它之前不要将指针设置为 NULL,但在它之后,否则你在 NULL 上调用 free,这是没有意义的。 (*head) 取消对头指针(即node**)的引用,它为您提供node*,然后您可以使用它访问->next。谷歌运营商优先找出原因。成员访问 (->) 优先于取消引用 (*)。
  • 谢谢,感谢您的洞察力!
【解决方案2】:

这会奏效。您只需将 head 的 next 设置为 null 并释放 head。现在我们不能移动到第二个元素。所以我们不能释放节点。还要检查基本条件。希望对你有帮助

void freeListmembers(node *head){
node *temp=head;
if(head==NULL)//Base condition
return;
while(head->next!=NULL){
temp=head;//Moved temp to head. we will move head to next and free the previous node
head=head->next;
free(temp);
}
free(head);
return;

}

【讨论】:

  • 这不是一个非常清晰或简洁的释放列表的方法。它有效,但以一种非常迂回的方式。
  • 我同意。但是我尝试根据提出问题的人的想法进行修改。这样他就可以知道自己在做什么。
猜你喜欢
  • 2013-10-31
  • 2018-09-29
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多