关于删除链表节点的问题
A question about deleting a node in a linked list
在调用 free() 之前;如果我不为要删除的节点的 link 部分分配 NULL 值,将出现什么问题?查阅了其他网站一些删除节点的代码,发现link部分没有赋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);
}
没有,行
temp->next = NULL;
没有必要。一旦 free
被调用,temp
指向的节点中的任何数据都将变为无效,因此在该节点内的任何值在它们变为无效之前立即更改将无效。
由于这些语句,当为空列表调用时,此函数可以调用未定义的行为
struct node * temp = head;
head = temp->next;
因为在这种情况下 head
等于 NULL
。
该函数释放struct node
类型对象占用的内存。所以改变被删除的对象是没有意义的。这个声明
temp->next = NULL; //my question is in this line, is this line necessary?
是多余的。
和之前删除节点写入一样
temp->data = INT_MAX;
不影响榜单
函数看起来像
void deleteFirstNode()
{
if ( head != NULL )
{
struct node *temp = head;
head = head->next;
free( temp );
}
}
此外,定义依赖于全局变量的函数也不是一个好主意。在这种情况下,您将无法在程序中创建多个列表。最好将指向头节点的指针通过引用传递给函数 deleteFirstNode。
在这种情况下,函数看起来像
void deleteFirstNode( struct node **head )
{
if ( head != NULL )
{
struct node *temp = *head;
*head = ( *head )->next;
free( temp );
}
}
而且函数可以这样调用
deleteFirstNode( &head );
在调用 free() 之前;如果我不为要删除的节点的 link 部分分配 NULL 值,将出现什么问题?查阅了其他网站一些删除节点的代码,发现link部分没有赋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);
}
没有,行
temp->next = NULL;
没有必要。一旦 free
被调用,temp
指向的节点中的任何数据都将变为无效,因此在该节点内的任何值在它们变为无效之前立即更改将无效。
由于这些语句,当为空列表调用时,此函数可以调用未定义的行为
struct node * temp = head;
head = temp->next;
因为在这种情况下 head
等于 NULL
。
该函数释放struct node
类型对象占用的内存。所以改变被删除的对象是没有意义的。这个声明
temp->next = NULL; //my question is in this line, is this line necessary?
是多余的。
和之前删除节点写入一样
temp->data = INT_MAX;
不影响榜单
函数看起来像
void deleteFirstNode()
{
if ( head != NULL )
{
struct node *temp = head;
head = head->next;
free( temp );
}
}
此外,定义依赖于全局变量的函数也不是一个好主意。在这种情况下,您将无法在程序中创建多个列表。最好将指向头节点的指针通过引用传递给函数 deleteFirstNode。
在这种情况下,函数看起来像
void deleteFirstNode( struct node **head )
{
if ( head != NULL )
{
struct node *temp = *head;
*head = ( *head )->next;
free( temp );
}
}
而且函数可以这样调用
deleteFirstNode( &head );