AlgoLab
AlgorithmsCompare
AlgoLab
AlgorithmsCompareGitHub

© 2026 AlgoLab. Open source.

AlgorithmsLinked ListsLinked List Insertion
Linked Listsbeginnerinsertionpointerdynamic

Linked List Insertion

Linked List Insertion adds a new node at a desired position. Inserting at the head is O(1) — just update the head pointer. Inserting at the tail requires traversal to find the last node (O(n) without a tail pointer). Inserting at position k requires traversal to node k-1.

Complexity

Best
O(1)
Average
O(n)
Worst
O(n)
Space
O(1)

Visualizer

Implementation

struct Node { int val; Node* next; Node(int v): val(v), next(nullptr){} };
Node* insertHead(Node* head, int val) {
    Node* node = new Node(val);
    node->next = head;
    return node;
}
Node* insertAt(Node* head, int pos, int val) {
    if (pos == 0) return insertHead(head, val);
    Node* curr = head;
    for (int i = 0; i < pos-1 && curr; i++) curr = curr->next;
    if (!curr) return head;
    Node* node = new Node(val);
    node->next = curr->next;
    curr->next = node;
    return head;
}

How It Works

1.Insert at Head

Create a new node, set its next to the current head, then update head to the new node. This is O(1) and the most common insertion for stack-like behavior.

2.Insert at Position

Traverse to node at position k-1, then set new_node.next = curr.next and curr.next = new_node. The key is updating pointers in the right order to avoid losing the rest of the list.

3.Insert at Tail

Without a tail pointer, insertion at the end requires O(n) traversal. With a dedicated tail pointer, tail insertion is O(1) — a common optimization for queue implementations.

Related Algorithms

Link2Linked List TraversalLink2Linked List DeletionLink2Linked List Reversal

Test Your Knowledge

Quiz coming soon for this algorithm.

Back to all algorithms