Deleting from the Head of a Doubly Linked List
What you'll learn: How to safely remove the first node from a doubly linked list while maintaining both forward and backward links.
The Core Idea
When you delete the head of a doubly linked list, you're removing the first node and making the second node (if it exists) the new head. The tricky part is correctly updating the previous pointer of this new head to be NULL, since it's now the first node with nothing before it.
Think of it like removing the first person from a line where everyone is holding hands with the person in front and behind them. When the first person leaves, the second person needs to let go with their backward hand (set it to NULL) since there's no one in front anymore.
The Process Step-by-Step
- Check if the list is empty: If
headisNULL, there's nothing to delete - Store the node to delete: Keep a temporary pointer to the current head so you can deallocate it later
- Move the head pointer forward: Update
headto point to the second node (head = head->next) - Update the new head's previous pointer: If the new head exists (list wasn't just one node), set
head->previous = NULL - Free the old head: Deallocate the memory of the node you removed
Why the Previous Pointer Matters
Unlike singly linked lists, you must remember to update the previous pointer. Forgetting this step leaves a dangling pointer pointing to freed memory—a serious bug that can crash your program or cause unpredictable behavior.
Key Takeaway: Deleting from the head of a doubly linked list requires moving the head pointer forward and setting the new head's previous pointer to NULL to maintain proper bidirectional links.