So I'm stuck trying to solve this exercise from a book (C Programming: A Modern Approach - K.N. King Chapter 17 exercise 6):
Modify the delete_from_list function so that it uses only one pointer variable instead of two (cur and prev).
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 = cur->next)
;
if (cur == NULL)
return list;
if (prev == NULL)
list = list->next;
else
prev->next = cur->next;
free(cur);
return list;
}
(The function returns the head of the list)
One way to do it would be to change the first function parameter to a pointer to pointer but that is asked in a following exercise.
I really can't think of a way to solve this using only one local variable without a memory leak or undefined behavior. Something like this:
struct node *delete_from_list(struct node *list, int n)
{
struct node *p = list;
if (!p)
return NULL;
if (p->value == n) {
list = list->next;
free(p);
return list;
}
while (p->next && p->next->value != n)
p = p->next;
if (p->next)
// free(p->next); // undefined behavior
p->next = p->next->next; // memory leak
return list;
}
Another way is recursion but I could never think of this by myself. I doubt this is the intention of the exercise since the exercises in this book are not complicated (this is the first one that I can't figure out) and there were only a few simple recursion exercises in a previous chapter. Also I think technically it's not really one local variable because each call of the function gets new variable copies.
struct node *delete_from_list(struct node *list, int n)
{
struct node *t;
if (list == NULL)
return NULL;
if (list->value == n) {
t = list->next;
free(list);
return t;
}
list->next = delete_from_list(list->next, n);
return list;
}
So is there any other way to do this?