我需要创建一个函数来删除 c 中链表的前 n 个节点,并返回删除的节点数。如果列表小于 n,它应该变为空。 另外,我不能使用递归。
使用现在的代码,它可以工作,但我没有释放“已删除”节点的内存。如果我取消注释应该释放内存的部分,我会在 codeboard.io 上收到此错误:
Input: 5 + [ 61 62 63 64 65 66 ]
Output: expected 5 + [ 66 ]
obtained 5 + [19333664 ]
那个随机数似乎是它正在访问内存中的“垃圾”。 如何正确释放不再使用的节点?
listas.h 中的代码:
typedef struct lligada {
int valor;
struct lligada *prox;
} *LInt;
LInt newLInt (int, LInt);
int drop (int, LInt *);
listas.c 中的代码
#include <stdlib.h>
#include "listas.h"
int drop (int n, LInt *l){
int count = 0;
LInt *aux;
while(n>0 && (*l)!=NULL){
n--;
count++;
//aux = &((*l));
*l = (*l)->prox;
//free(*aux);
}
return count;
}
练习的代码板链接:https://codeboard.io/projects/16259
最佳答案
请注意,LInt
定义为指向 struct lligada
的指针。因此,drop
函数的 l
参数是指向 struct lligada
的指针。让我们调用 l
指向 list_head
的 LInt
变量。
所以,行:
aux = &((*l));
实际上是将 aux
分配给 list_head
的地址,而不是 list_head
指向的 struct lligada
。
因此,解决方案是将 aux
定义为 LInt
然后执行:
aux = *l;
*l = (*l)->prox;
free(aux);
希望对您有所帮助。
关于C - 链表 : free() function is deleting my head node; how do I use free() correctly?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37330376/