Skip to main content

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:

  1. Check that begin_list is not NULL (safety guard).
  2. Loop while *begin_list points to a valid node.
  3. If cmp returns 0 (match), save the node in temp, redirect *begin_list to skip it, then free(temp).
  4. If no match, advance by pointing begin_list to the address of the current node's next pointer.

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.