I’ve got a structure:
struct Node {
int value;
struct Node *next;
};
typedef struct Node List;
And I’ve implemented adding items to the list but I’ve got problem with removing element from the list when it’s the first element on given list, my function:
void removeItem(List *ptr, int i)
{
List *current = ptr;
List *prev = NULL;
while (current != NULL)
{
if (current->value == i)
{
//it's first element
if (prev == NULL)
{
List *replace = ptr->next;
free(current);
ptr = replace;
current = replace;
}
else
{
prev->next = current->next;
free(current);
current = prev->next;
}
}
else
{
prev = current;
current = current->next;
}
}
}
When my list is like:
1, 2, 3, 4, 5
After using removeItem(list, 1) it’s:
0, 2, 3, 4, 5
0 shouldn’t be there.
Another question is that I should also implement those functions when typedef is different:
typedef struct Node *List;
But then I get tons of “wrong argument type” / “request for member ‘value’ in something not a structure or union” errors. Can I find some example of how this should be handled?
Your problem is that the variable that you pass in (
list) does not get modified by your remove code. Thus, when you remove the firstNodein yourList, you’re left with a reference to aNodethat is no longer in yourList.The reason is this:
When you call
removeItem(list, 1), you’re passing in the value oflist. In this case, it’s an address of data with typeList. Inside theremoveItemfunction, that value is carried by theptrvariable. When you enter the function, theptrvariable is the address of yourListand you do your work with it. In the lineptr = replace, all you’re doing is changing the value held byptr. It does not affect the value oflistwithin the scope thatremoveItemwas called.The simplest thing to do would be for
removeListto return a pointer to the head of the resulting list. For most calls, it will be the same as the incomingptr; only when the removedNodeis at the head of theList, will the resulting pointer be different.Alternatively, you could change
removeListso that it requires a pointer to a pointer to aList, then you would call it asremoveList(&list, 1)and this would allow you to modify the value inlistdirectly.