I’m trying to write a function that removes a certain value from a linked list and return back the whole list. However, my problem at the moment is to return the list that points to the first item, not the last one after looping through the list.
The code looks like:
static LISTITEM *removeItem(LISTITEM *list, int n) {
LISTITEM *thislist = list;
while (thislist != NULL) {
if (thislist->value == n) {
LISTITEM *old;
old = thislist;
thislist = thislist->next;
free(old);
}
thislist = thislist->next;
}
return thislist;
}
The code executed with no errors, but when I try to print the stack list, it doesn’t print anything after this function is called (means the original list was printed ok).
I guess the problem is because when thislist is returned, it’s currently at the last element on the list because of the loop.
You need to return
listinstead ofthislist. It becomes clearer if you renamelisttoheadandthislisttocurrent.Also: You are not removing your item from the list. All you do is freeing some memory and keeping the pointers to it. So the next time you iterate over your list it might crash.
To fix it you need to keep a
previouspointer for the previous element. Once you found your element you need toprevious->next = current->next. Only then nothing will point to the current element and you can safely free it (unless you store the pointer somewhere else as well).Apparently there is a special case: when the head is the item you want to remove (then you don’t have a previous item) – I’ll leave that to you to figure out 🙂
As a side note: once you fixed your code you will remove all occurences of
nfrom the list as it stands – this might or might not be what you want (consider to leave the while loop when you found your element)