Deleting from the Middle of a Doubly Linked List
What you'll learn: How to remove a node from the middle of a doubly linked list by carefully updating the next and previous pointers of its neighbors.
The Core Idea
When deleting a node from the middle of a doubly linked list, you need to "stitch together" the nodes on either side of the one you're removing. Think of it like removing a person from a line where everyone is holding hands with both neighbors—you need to reconnect the person on the left to the person on the right, and vice versa.
The Process
Unlike singly linked lists (where you only worry about next pointers), doubly linked lists require updating both directions:
- Make the previous node point forward past the node being deleted
- Make the next node point backward past the node being deleted
- Deallocate the removed node to prevent memory leaks
Example Steps
Say you want to delete the middle node containing 20:
[10] ⇄ [20] ⇄ [30]
You would:
- Set
10'snextpointer to point to30(bypassing20) - Set
30'spreviouspointer to point back to10(bypassing20) - Free the memory of node
20
Result:
[10] ⇄ [30]
Why Both Pointers Matter
If you only updated one direction, your list would break—traversing forward would work but traversing backward wouldn't (or vice versa). The bidirectional nature of doubly linked lists means you must maintain both links for consistency.
Key Takeaway: Deleting from the middle of a doubly linked list requires updating both the next pointer of the previous node and the previous pointer of the next node, effectively removing the target node from both directions of traversal.