Bird
0
0
DSA Cprogramming

Insert at Middle Specific Position in DSA C

Choose your learning style9 modes available
Mental Model
We add a new item exactly where we want in the list by moving step-by-step to that spot and linking the new item there.
Analogy: Imagine a line of people holding hands. To add a new person in the middle, you find the right spot, then the new person holds hands with the next person, and the previous person holds hands with the new person.
head -> 1 -> 2 -> 3 -> null
          ↑
       position 2
Dry Run Walkthrough
Input: list: 1 -> 2 -> 3 -> null, insert value 4 at position 2
Goal: Insert the value 4 between nodes 1 and 2, so the list becomes 1 -> 4 -> 2 -> 3 -> null
Step 1: create new node with value 4
head -> 1 -> 2 -> 3 -> null
new_node: 4 -> null
Why: We need a new node ready to insert
Step 2: start at head node 1, move to position 1 (one step before position 2)
head -> [curr->1] -> 2 -> 3 -> null
new_node: 4 -> null
Why: We stop before the insertion point to link new node
Step 3: link new node's next to curr's next (node 2)
head -> [curr->1] -> 2 -> 3 -> null
new_node: 4 -> 2 -> 3 -> null
Why: New node points to the node currently at position 2
Step 4: link curr's next to new node
head -> 1 -> [new_node->4] -> 2 -> 3 -> null
Why: Previous node now points to new node, completing insertion
Result:
head -> 1 -> 4 -> 2 -> 3 -> null
Annotated Code
DSA C
#include <stdio.h>
#include <stdlib.h>

// Define node structure
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// Function to create a new node
Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// Insert at specific position (1-based index)
void insertAtPosition(Node** head, int data, int position) {
    Node* newNode = createNode(data); // create new node

    if (position == 1) { // insert at head
        newNode->next = *head; // new node points to current head
        *head = newNode; // head updated to new node
        return;
    }

    Node* curr = *head;
    int count = 1;
    // move curr to node before insertion point
    while (curr != NULL && count < position - 1) {
        curr = curr->next; // advance curr
        count++;
    }

    if (curr == NULL) { // position is beyond list length
        free(newNode); // avoid memory leak
        return; // do nothing
    }

    newNode->next = curr->next; // new node points to next node
    curr->next = newNode; // previous node points to new node
}

// Print list
void printList(Node* head) {
    Node* curr = head;
    while (curr != NULL) {
        printf("%d -> ", curr->data);
        curr = curr->next;
    }
    printf("null\n");
}

int main() {
    // Create initial list: 1 -> 2 -> 3 -> null
    Node* head = createNode(1);
    head->next = createNode(2);
    head->next->next = createNode(3);

    // Insert 4 at position 2
    insertAtPosition(&head, 4, 2);

    // Print final list
    printList(head);

    return 0;
}
Node* newNode = createNode(data);
create new node to insert
if (position == 1) { newNode->next = *head; *head = newNode; return; }
handle insertion at head
while (curr != NULL && count < position - 1) { curr = curr->next; count++; }
move curr to node before insertion point
if (curr == NULL) { free(newNode); return; }
handle position beyond list length
newNode->next = curr->next; curr->next = newNode;
link new node into list
OutputSuccess
1 -> 4 -> 2 -> 3 -> null
Complexity Analysis
Time: O(n) because we may need to traverse up to n nodes to reach the insertion point
Space: O(1) because we only create one new node and use a few pointers
vs Alternative: Compared to inserting at head or tail which can be O(1), inserting in the middle requires traversal, so it is slower but necessary for precise placement
Edge Cases
insert at position 1 (head insertion)
new node becomes the new head
DSA C
if (position == 1) { newNode->next = *head; *head = newNode; return; }
insert at position beyond list length
no insertion happens, new node is freed
DSA C
if (curr == NULL) { free(newNode); return; }
insert into empty list at position 1
new node becomes the head
DSA C
if (position == 1) { newNode->next = *head; *head = newNode; return; }
When to Use This Pattern
When you need to add an item exactly at a certain spot in a list, use the insert at position pattern to carefully link the new node in place.
Common Mistakes
Mistake: Not stopping at the node before the insertion position, causing incorrect links
Fix: Traverse until position - 1 to correctly link the new node
Mistake: Not handling insertion at head separately, leading to lost head pointer
Fix: Check if position is 1 and update head pointer accordingly
Mistake: Not checking if position is beyond list length, causing null pointer errors
Fix: Check if current node is NULL before insertion and handle gracefully
Summary
It inserts a new node at a given position inside a linked list.
Use it when you want to add an element not just at the start or end, but somewhere in the middle.
The key is to stop at the node before the insertion point and link the new node between nodes.