[英]How to clear a linked list using double pointer?
Hi I'm trying to make a function that clears a linked list that *first
will point to, then the node **first
should be freed and the pointer *first
set to NULL
. 嗨,我正在尝试创建一个清除
*first
指向的链接列表的函数,然后**first
释放节点**first
并将指针*first
设置为NULL
。
I'm having trouble grasping double pointers and can't get this to work correctly. 我在抓双指针时遇到麻烦,无法使其正常工作。
You have to move to the next list element before you delete the node. 在删除节点之前,必须移动到下一个列表元素。 Otherwise you are accessing memory that has been freed.
否则,您正在访问已释放的内存。
while( *first != NULL )
{
temp = *first;
*first = temp->next;
free(temp);
}
Be aware that because you're trashing the whole list, *first
is going to eventually be NULL. 请注意,因为您正在废弃整个列表,
*first
将最终为NULL。 So you can use a single-pointer (just like temp
) to traverse your list, and then set *first = NULL
at the end. 因此,您可以使用单指针(就像
temp
一样)遍历列表,然后在结尾处设置*first = NULL
。 That saves an extra pointer indirection, which arguably is wasteful of CPU in this case. 这节省了额外的指针间接,在这种情况下可以说是浪费CPU。
[edit] What I mean is: [编辑]我的意思是:
struct node *curr = *first;
struct node *prev;
while( curr != NULL )
{
prev = curr;
curr = curr->next;
free(prev);
}
*first = NULL;
Generally, I find that the less pointer dereferencing you have going on, the easier the code is to understand at a glance. 一般来说,我发现指针解除引用的指针越少,代码一目了然就越容易理解。
node* remove_node(node **double_pointer,int search_value)
//pass head of your node as a parameter to double pointer
{while(*double_pointer && **(double_pointer).value!=search_value)
{
double_pointer=&((**double_pointer)->next);
}
if(**double_pointer!=null)
{//lines below are to delete the node which contains our search value
node* deleted_node=*double_pointer;
*double_pointer=*double_pointer->next;
return deleted node;
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.