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

Deleting without head traversal

Deleting without head traversal

What you'll learn: How to remove a node from a Doubly Linked List in constant time by utilizing its backward and forward pointers.

The Power of Two-Way Streets

In a standard Singly Linked List, deleting a specific node is like being on a one-way street. If you are standing at "Node C" and want to delete it, you are stuck. You need to know who is behind you (Node B) so you can tell them to point to the person in front of you (Node D). Because you can't look backward, you have to start at the very beginning (the Head) and walk through the list until you find the node right before C. This takes time—specifically O(n)O(n) time.

In a Doubly Linked List (DLL), every node has a prev pointer. This changes everything. If you have a pointer to the node you want to delete, you can "look behind you" instantly. You don't need to start at the Head. You can perform the surgery right where you stand.

Stitching the Gap

Think of a DLL like a line of people holding hands. Each person has a left hand (prev) and a right hand (next). To remove a person from the middle, you simply tell the person to their left to grab the hand of the person to their right, and vice versa.

Here is how we bypass the current node:

struct Node {
    int data;
    struct Node* next;
    struct Node* prev;
};

void deleteNode(struct Node* target) {
    // Safety check: make sure the node exists
    if (target == NULL) return;

    // If there is a node before us, tell it to skip over us
    if (target->prev != NULL) {
        target->prev->next = target->next;
    }

    // If there is a node after us, tell it to reach back to our predecessor
    if (target->next != NULL) {
        target->next->prev = target->prev;
    }

    // Now that the list is stitched together, we can safely remove the target
    free(target);
}

Why this matters

By using the prev pointer, we eliminate the need for a while loop to find the predecessor. We go from "searching the whole line" to "instant removal." This is known as O(1)O(1) or constant time complexity.

However, there is a small catch: if the node you are deleting is the Head, you must still update your Head pointer variable in your main program to point to target->next, otherwise your program will try to start the list at a memory location that no longer exists.

Key takeaway

Doubly Linked Lists allow for O(1)O(1) deletion because each node inherently knows its predecessor, removing the need to traverse from the head.