C 链表销毁函数 [英] C Linked-list Destroy Function

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

问题描述

我正在尝试学习 C,和很多人一样,我对指针有点卡住了.无论如何,我做了一个递归函数来破坏我的链表,但正如我调试的那样,当我从函数中返回时,列表的头部并不像它应该的那样为空,所以我猜这是对指针的一些基本误解.这是函数:

I am trying to learn C, and as many people, I have been a little stuck with pointers. Anyways, I made a recursive function that destroys my linked list, but as I have debugged, when I am back from the function the head of the list is not null as it should be, so I'm guessing it's some basic misunderstanding with pointers. Here's the function:

void destroy(struct node *n) {
   if (!n) return;
   destroy(n->next);
   free(n);
   n = NULL;
}

推荐答案

void deleteList(struct node** head_ref)
{  
  struct node* current = *head_ref;
  struct node* next;
  while (current != NULL) {
    next = current->next;
    free(current);
    current = next;
  }
  *head_ref = NULL;
}

尝试这样....您可以根据需要更改名称.如果您仍然需要帮助,请告诉我.

Try like this ....you can change names as you want. If you still need help let me know.

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

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