ft_list_remove_if — Remove Matching List Elements
Allowed functions: free
Write a function that removes from the passed list any element the data of which is "equal" to the reference data.
void ft_list_remove_if(t_list **begin_list, void *data_ref, int (*cmp)());
cmp takes two void* and returns 0 when both parameters are equal.
Solution
Download ft_list_remove.c#include "ft_list.h"
#include <stdlib.h>
void ft_list_remove_if(t_list **begin_list, void *data_ref, int (*cmp)()) {
t_list *temp;
if (!begin_list)
return;
while (*begin_list) {
if (cmp((*begin_list)->data, data_ref) == 0) {
temp = *begin_list;
*begin_list = (*begin_list)->next;
free(temp);
} else
begin_list = &(*begin_list)->next;
}
}
How It Works
Goal: Remove all nodes from a linked list whose data matches a reference value.
Approach: Use a pointer-to-pointer to walk the list, unlinking and freeing matching nodes in place.
Step by step:
- Check that
begin_listis not NULL (safety guard). - Loop while
*begin_listpoints to a valid node. - If
cmpreturns 0 (match), save the node intemp, redirect*begin_listto skip it, thenfree(temp). - If no match, advance by pointing
begin_listto the address of the current node'snextpointer.
Key concept: Pointer-to-pointer (t_list **) for in-place list modification — it lets you update the previous node's next (or the head pointer) without needing a separate "prev" variable.