Inserting in the Middle of a Doubly Linked List
You'll learn how to insert a node at any position in a doubly linked list by carefully managing four pointer connections.
The Core Challenge
Unlike inserting at the head or tail, inserting in the middle of a doubly linked list requires updating four pointers: two in the new node and one in each of its neighboring nodes. Miss any one of these, and your list breaks.
The Four-Pointer Dance
Think of it like inserting a new link into a double-sided chain. You must:
- Connect the new node's
prevpointer to the node before it - Connect the new node's
nextpointer to the node after it - Update the previous node's
nextpointer to point to the new node - Update the next node's
prevpointer to point back to the new node
The order matters! You must preserve the existing connection between the two neighbors before breaking it.
The Safe Sequence
// Assume we're inserting "newNode" between "current" and "current->next"
newNode->next = current->next; // 1. New node points forward
newNode->prev = current; // 2. New node points backward
current->next->prev = newNode; // 3. Next neighbor points back to new node
current->next = newNode; // 4. Previous neighbor points to new node
Notice we store current->next in the new node first, preserving access to the next neighbor before we overwrite current->next.
Edge Cases
Always check if you're actually inserting in the middle versus at the boundaries (head or tail), which may require different logic.
Key Takeaway: Inserting in the middle of a doubly linked list requires updating exactly four pointers in the correct order to maintain bidirectional connectivity without losing access to neighboring nodes.