[英]How can I delete an node from a linked list with a single pointer?
The book I study #include
an exercise that asks us for modifying the following code which deletes a node from a linked list and building another function that does the exact thing with only one pointer:我研究的这本书#include
一个练习,要求我们修改以下代码,该代码从链表中删除一个节点,并构建另一个仅用一个指针执行完全相同操作的函数:
struct node {
int value;
struct node * next;
};
struct node delete_from_list( struct node * list , int n){
struct node *cur, *prev;
for (cur = list, prev = NULL;
cur != NULL && cur -> value != n;
prev = cur, cur -> next)
;
if(cur == NULL)
return list;
else if(prev == NULL)
list = list -> next;
else
prev -> next = cur -> next;
free(cur);
return list;
}
Some code I've seen online is:我在网上看到的一些代码是:
struct node *delete_from_list(struct node **list, int n) {
struct node *entry = *list;
while (entry) {
if (entry->value == n) {
*list = entry->next;
free(entry);
break;
}
list = &entry->next;
entry = entry->next;
}
return *list;
}
But i have two objections for this:但我对此有两个反对意见:
This code contains two pointers actually entry
and list
.这段代码实际上包含两个指针entry
和list
。
We are free()
ing the entry
yet proceed to use it which "feels" like an error.我们是free()
输入entry
但继续使用它“感觉”像一个错误。
Please, if you are willing to help, either explain my objections or write a new code.请,如果您愿意提供帮助,请解释我的反对意见或编写新代码。 Thanks.谢谢。
- This code contains two pointers actually
entry
andlist
.这段代码实际上包含两个指针entry
和list
。
You are required to build an algorithm that uses a single pointer.您需要构建一个使用单个指针的算法。 In your case, though it seems like two, entry
is that one pointer which the algorithm uses apart from list
which is actually an input to the function containing the algorithm .在您的情况下,尽管看起来像两个,但entry
是算法使用的一个指针,除了list
之外,它实际上是包含 algorithm的函数的输入。
- We are
free()
ing the entry yet proceed to use it which "feels" like an error.我们是free()
输入条目,但继续使用它“感觉”像一个错误。
The code doesn't use entry
after freeing it.该代码在释放它后不使用entry
。 Once freed, the loop breaks immediately due to the break
statement succeeding the call to free
.一旦释放,循环立即中断,因为break
语句在调用free
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.