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:
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
.
We are free()
ing the entry
yet proceed to use it which "feels" like an error.
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
.
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 .
- We are
free()
ing the entry yet proceed to use it which "feels" like an error.
The code doesn't use entry
after freeing it. Once freed, the loop breaks immediately due to the break
statement succeeding the call to free
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.