Delete a node with a given value from a singly linked list.
int delete_value(node_t **head, int v)
{
for (node_t **pp = head; *pp; pp = &(*pp)->next) {
if ((*pp)->val == v) {
node_t *dead = *pp;
*pp = dead->next; /* unlink: works for head and inner nodes */
free(dead);
return 0;
}
}
return -1; /* not found */
}
Points: the double-pointer technique avoids tracking prev and special-casing the head; free the node after unlinking; return a status if not found. To delete all matches, do not advance pp after a deletion.