我在考试中遇到了一个问题。
编写一个函数DeleteList
(),它获取一个列表,释放它的所有内存并设置它的head指针指向NULL(空列表)。
解为
void DeleteList(struct node** headRef) {
struct node* current = *headRef;
struct node* next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
*headRef = NULL;
}
我的解决方案:
void DeleteList(struct node** headRef) {
struct node* current = *headRef;
while (current != NULL) {
*headRef = *headRef->next;
free(current);
current = * headRef;
}
free(current);
*headRef = NULL;
}
这个方法正确吗?谢谢你,
您的解决方案不会这样做"并将其头部指针设置为NULL",因为您的建议(*headRef = NULL;
)的最后一行不再将传入的headRef值设置为NULL,而是将列表中的最终Next点(已经为NULL)
free(current); //you should remove this line after the while loop because when while loop breaks the current is already NULL so free(NULL) makes no sense.
*headRef = NULL;
看这里Free(NULL).
void DeleteList(struct node **headRef)
{
struct node *current = *headRef;
while (current) {
*headRef = (*headRef)->next;
free(current);
current = *headRef;
}
*headRef = NULL;
}