Inserting in a doubly linked list
What you'll learn: How to update four specific pointers to tuck a new node between two existing neighbors.
In a singly linked list, inserting a node is like a game of follow-the-leader. You only need to tell the new person who to follow. In a doubly linked list, it’s more like joining a human chain where everyone is holding both hands. To squeeze in, you have to grab the hand of the person in front of you, the hand of the person behind you, and convince them to hold yours in return.
The four-way handshake
When you insert a new node (new_node) between two existing nodes (prev_node and next_node), you must update four pointers to maintain the integrity of the chain. If you miss even one, the chain breaks, and you'll likely run into a segmentation fault or a memory leak.
- New Node's Next: Point
new_node->nextto thenext_node. - New Node's Prev: Point
new_node->prevto theprev_node. - Forward Link: Point
prev_node->nextto thenew_node. - Backward Link: Point
next_node->prevto thenew_node.
Seeing it in code
Assume we are inserting a node in the middle of a list. We have a pointer to the node that should come before our new entry.
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
void insertAfter(struct Node* prev_node, int new_data) {
if (prev_node == NULL) return;
// 1. Allocate memory and set data
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
// 2. Connect new node to the rest of the list
new_node->next = prev_node->next;
new_node->prev = prev_node;
// 3. Update the 'next' neighbor to point back to us
if (new_node->next != NULL) {
new_node->next->prev = new_node;
}
// 4. Update the 'prev' neighbor to point forward to us
prev_node->next = new_node;
}
Safety first
The order of these steps matters. Always set the new_node pointers first. If you update prev_node->next before you've saved its value into new_node->next, you lose your connection to the rest of the list—it’s like dropping the hand of the person behind you before the new person has grabbed it.
Key takeaway
Inserting in a doubly linked list requires a "four-way handshake" to ensure both the forward and backward paths remain unbroken.