Course contentsShow
← Computer Science
Lesson 343 of 2,8728. Linked Data StructuresFree lesson

Inserting in the Middle of a Doubly Linked List

Inserting a node at an arbitrary position while updating four pointer connections correctly.

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:

  1. Connect the new node's prev pointer to the node before it
  2. Connect the new node's next pointer to the node after it
  3. Update the previous node's next pointer to point to the new node
  4. Update the next node's prev pointer 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.