Data Structures · Visualization
Doubly LL: Insert at Index
Doubly Linked List
Inserting at a chosen index places a new node between two existing neighbors. Time: O(n) to reach the index, O(1) to relink. Space: O(1).
Big-O: Insert/delete at either end O(1); extra memory for prev pointers.
Doubly LL: Insert at Index
Doubly Linked ListInserting at a chosen index places a new node between two existing neighbors. You walk to the target position (from whichever end is closer, since the list can be traversed both ways) and then rewire four pointers: the new node's next/prev, and its new neighbors' prev/next.
How Insert at Index Works
- Traverse to the node currently at the target index, call it 'current'.
- Set newNode.prev to current.prev and newNode.next to current.
- Set current.prev.next to newNode (if current.prev exists).
- Set current.prev to newNode.
Insert at Index Worked Example
Input: Insert 99 at index 1 into null <- 1 <-> 2 <-> 3 -> null
- current = node at index 1 (value 2)
- newNode(99).prev = current.prev (node 1); newNode(99).next = current (node 2)
- node1.next = newNode(99)
- node2.prev = newNode(99)
Output: null <- 1 <-> 99 <-> 2 <-> 3 -> null
Press ▶ Run to watch it step by step.
def push_front(head, val):
node = Node(val)
node.next = head
if head:
head.prev = node
return node # new head O(1)
def push_back(head, tail, val):
node = Node(val)
node.prev = tail
if tail:
tail.next = node
return node # new tail O(1)
# example: insert 99 at index 1 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 new song into a specific spot in a playlist
- Keeping a sorted doubly linked list in order
- Editors that insert content at a cursor position
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.