Data Structures · Visualization
Linked List: Insert at Index
Linked List
Inserting at a specific index places a new node between two existing nodes at that position. Time: O(n) to reach the index, O(1) to relink once there. Space: O(1).
Big-O: Lookup O(n); insert/delete at head O(1).
Linked List: Insert at Index
Linked ListInserting at a specific index places a new node between two existing nodes at that position. You first need to walk the list to find the node just before the target index, then re-point the links so the new node slots in between.
How Insert at Index Works
- If the index is 0, insert at the front and stop.
- Traverse the list, counting nodes, until you reach the node just before the target index (the 'previous' node).
- Point the new node's 'next' to previous.next (the node currently at the target index).
- Point previous.next to the new node.
Insert at Index Worked Example
Input: Insert 99 at index 2 into head -> 1 -> 2 -> 3 -> null
- Traverse to index 1 (value 2) — this is 'previous'
- newNode(99).next = previous.next (node 3)
- previous.next = newNode(99)
Output: head -> 1 -> 2 -> 99 -> 3 -> null
Press ▶ Run to watch it step by step.
def insert_front(head, val):
node = Node(val)
node.next = head
return node # new head O(1)
def insert_end(head, val):
node = Node(val)
if not head:
return node
cur = head
while cur.next: # walk to tail O(n)
cur = cur.next
cur.next = node
return head
# example: insert 99 at index 2 on [1, 2, 3]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Insert at Index Time & Space Complexity
When to Use Insert at Index
- Inserting a task at a specific priority position in a task list
- Keeping a sorted linked list in order as new values arrive
- Editing operations in text editors represented as linked structures
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.