Course contentsShow
← C
Lesson 996 of 1,21914. Data Structures in CFree lesson

Deleting a node by value

Deleting a node by value

What you'll learn: How to search for a specific piece of data in a linked list and reroute the pointers to remove that node from the chain.

The "Bridge" Concept

Imagine a line of people holding hands. Each person (a node) holds the hand of the person behind them. If you want to remove "Dave" from the middle of the line, you can’t just tell Dave to leave. If he let go, the line would break in two. Instead, you must tell the person before Dave to let go of Dave’s hand and grab the hand of the person after Dave.

In C, deleting a node by value involves two main steps: finding the target and "bridging" the gap.

The Two-Pointer Approach

To delete a node, we need to know who the "previous" node is. Since singly linked lists only point forward, we usually use two pointers while traversing:

  1. temp: To find the node we want to delete.
  2. prev: To keep track of the node just before it so we can update its next pointer.

Implementation

Here is how you handle the three scenarios: the list is empty, the head is the target, or the target is deeper in the list.

void deleteNode(struct Node** head_ref, int key) {
    struct Node *temp = *head_ref, *prev = NULL;

    // 1. If the head node itself holds the value to be deleted
    if (temp != NULL && temp->data == key) {
        *head_ref = temp->next; // Changed head
        free(temp);             // Free old head
        return;
    }

    // 2. Search for the value to be deleted, keep track of the previous node
    while (temp != NULL && temp->data != key) {
        prev = temp;
        temp = temp->next;
    }

    // 3. If the value was not present in the list
    if (temp == NULL) return;

    // 4. Unlink the node from the linked list
    prev->next = temp->next;

    // 5. Free the memory
    free(temp);
}

Important Considerations

  • Memory Management: Always use free() on the node you remove. If you don't, that memory remains "leaked" and unusable by your program.
  • The Head Case: If the first node is the one you are deleting, you must update the head pointer itself, otherwise your program will still try to start the list at a node that no longer exists.
  • Safety: Always check if temp is NULL during your search. If you reach the end of the list without finding the value, you must stop to avoid a segmentation fault.

Key takeaway

To delete a node, you must update the next pointer of the preceding node to skip over the target, then free the target's memory.