Lesson 9 of 14
Delete by Value
Deleting a Node by Value
Deleting a node from the middle of the list requires a previous pointer — you need to update the preceding node's next to skip the deleted node.
struct Node *delete_val(struct Node *head, int val) {
if (head == NULL) return NULL;
if (head->val == val) {
struct Node *next = head->next;
free(head);
return next;
}
struct Node *prev = head;
struct Node *cur = head->next;
while (cur != NULL) {
if (cur->val == val) {
prev->next = cur->next;
free(cur);
return head;
}
prev = cur;
cur = cur->next;
}
return head;
}
The Three Cases
- List is empty — return
NULL - Head matches — new head is
head->next; free old head - Middle/tail matches — set
prev->next = cur->next; freecur
Delete 3 from [1] -> [2] -> [3] -> [4] -> NULL
prev cur
[2] -> [3] -> [4]
[2] → × → [4]
Result: [1] -> [2] -> [4] -> NULL
Only the First Occurrence
This removes the first node with the matching value. If duplicates exist, they remain.
Your Task
Implement struct Node *delete_val(struct Node *head, int val) that removes the first occurrence of val and returns the new head.
TCC compiler loading...
Loading...
Click "Run" to execute your code.