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
entryandlist.We are
free()ing theentryyet 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.
break;entrypointing to a block of two boxes which means astruct nodestructure. And usingfree(entry)was just replacing the block of two boxes with a huge cross. It is right, isn't it?