首页 > 解决方案 > 关于删除链表中节点的问题

问题描述

在调用 free(); 之前 如果我没有为要删除的节点的链接部分分配 NULL 值,那么会出现什么问题?我查看了其他网站的一些删除节点的代码,但我发现没有为链接部分分配 NULL 值。他们只是调用了 free(); 功能。请回复以消除我的困惑。谢谢你。

struct node
{
 int data;
 struct node * next;
}

struct node * head = NULL; //This is the head node.

/* Here some other functions to create the list */
/* And head node is not going to be NULL here, after creating the list */

void deleteFirstNode()
{
 struct node * temp = head;
 head = temp->next;

 temp->next = NULL;  //my question is in this line, is this line necessary?

 free(temp);
}

标签: cmemory-managementstructlinked-listsingly-linked-list

解决方案


不,线

temp->next = NULL;

没有必要。所指向的节点中的任何数据都temp将在free被调用时立即变为无效,因此在该节点内的任何值变为无效之前立即更改该节点内的任何值都将无效。


推荐阅读