Inserting after a specific node
What you'll learn: How to stitch a new piece of data into the middle of a linked list by redirecting pointers.
Imagine a linked list as a scavenger hunt where each person holds a note pointing to the next person. If you want to insert a new person, "Sarah," directly after "Bob," you can't just shove her into a slot. You have to carefully swap the notes so the chain doesn't break.
The two-step "handshake"
To insert a node after a specific point (let's call it the prev_node), you must perform two critical steps in a specific order. If you do them out of order, you lose the rest of your list forever!
- The New Link: First, give the new node the address of the node that currently follows Bob. Now, both Bob and the new node are pointing to the same "next" person.
- The Re-link: Update Bob’s pointer to point to the new node.
By doing it in this order, you ensure that the new node "grabs hold" of the rest of the list before you break the old connection.
Seeing it in code
In C, we first check if the prev_node actually exists. Then, we perform the pointer swap.
struct Node {
int data;
struct Node* next;
};
void insertAfter(struct Node* prev_node, int new_data) {
// 1. Check if the given prev_node is NULL
if (prev_node == NULL) {
printf("The given previous node cannot be NULL");
return;
}
// 2. Allocate memory for the new node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
// 3. Make 'next' of new node as 'next' of prev_node
new_node->next = prev_node->next;
// 4. Move the 'next' of prev_node to point to new_node
prev_node->next = new_node;
}
Why the order matters
If you performed Step 4 before Step 3, prev_node->next would point to your new node immediately. You would have no way to find the rest of the list that used to follow it. It would be like cutting a rope before you've tied the new segment onto the tail end; the bottom half of the rope simply falls away into the abyss of your computer's memory (a memory leak).
Key takeaway
To insert in the middle, point the new node to the "next" neighbor first, then point the previous node to the new node.