I am doing an exercise from King. Can you give some hint. The following code deletes a node
Code:
struct node *delete_from_list(struct node *list, int n)
{
struct node *cur, *prev;
cur = malloc(sizeof(struct node));
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 cur;
}
Isn't it cheating that the returned list is a new list with out the unwanted value it is not the original list which still occupies memory? The question is to do this with just a single variable. So I have to lose one of cur, prev. My idea is to make a linked list from scratch and assign it only the desired value. My attempt is as follows. But its not working. I got lost somewhere out there.
Code:
struct node *delete_from_list(struct node *list, int n)
{
struct node *prev;
prev = malloc(sizeof(struct node));
for (prev->value = list->value; list!= NULL;list = list->next)
{
if (list->value !=n)
{
prev->value = list->value;
// In the prev next store the address that list next contains
// this line causes the error
*(prev->next) = *(list->next);
}
}
return prev;
compiler complains incompatible types when assigning to type ‘struct node *’ from type ‘struct node’