我正在努力学习C,而且和很多人一样,我一直被指针困住了。无论如何,我做了一个递归函数来销毁我的链表,但是当我调试时,当我从函数返回时,列表的头部不应该是空的,所以我猜它是一些基本的误解指针。这是功能:
void destroy(struct node* n){
if(!n) return;
destroy(n->next);
free(n);
n = NULL; }
提前致谢。
答案 0 :(得分:7)
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;
}
尝试这样....您可以根据需要更改名称。如果您仍需要帮助,请告诉我。
答案 1 :(得分:2)
当此函数结束时已释放头但它不为空。 C中的所有内容都按值传递。所以你将头部位置的副本传递给destroy。该内存已被释放,但头部未被更改。
您可以将其写为:
destroy(&head);
void destroy(struct node** n){
if(!*n) return;
destroy(&((*n)->next));
free(*n);
*n = NULL;
}
答案 2 :(得分:1)
您必须使用指向列表的指针,并使用destroy(&n)
调用:
/* clear complete list */
void destroy(struct node **n)
{
if (*n== NULL)
return;
if ((*n)->next == NULL)
{
free(*n);
*n= NULL;
}
else
{
struct node *iter = *n;
struct node *prev = NULL;
/* get last item and previous one */
while (iter->next != NULL)
{
prev = iter;
iter = iter->next;
}
prev->next = NULL;
free(iter);
/* repeat call */
clear(n);
}
}
希望这可以帮助你。
当我看到spt025的解决方案时,我的代码似乎有点太多了。我也只是一个初学者;)
答案 3 :(得分:0)
您的递归destroy
函数无法修改调用者框架中的head
变量。
语句n = NULL
仅影响函数参数,它是destroy
函数的局部变量。它实际上没有任何作用,因此您可以删除此语句。
如果需要在调用方函数中head
进行调用之后,应将NULL
设置为destroy
。
答案 4 :(得分:0)
以下是使用DeleteRear()
销毁链接列表的示例函数:
void Destroy_Using_Rear(List *L)
{
int y;
Node *P,*Q,*Z;
while(P!=NULL){
y=DeleteRear(L,x);
return y;
Z=P;
P=*L;
}
}