Data Structures · Visualization
Doubly LL: Insert at Front
Doubly Linked List
Inserting at the front adds a new node before the current head and connects it in both directions, then updates head to point to the new node. Time: O(1). Space: O(1).
Big-O: Insert/delete at either end O(1); extra memory for prev pointers.
Doubly LL: Insert at Front
Doubly Linked ListInserting at the front adds a new node before the current head and connects it in both directions, then updates head to point to the new node. Because there are two pointers per node, both the new node's links and the old head's back-link must be updated.
How Insert at Front Works
- Create a new node with the desired value.
- Set newNode.next to the current head.
- If the list is not empty, set head.prev to newNode.
- Update head to newNode; newNode.prev stays null.
Insert at Front Worked Example
Input: Insert 1 at front of null <- 2 <-> 3 -> null
- newNode(1).next = head (node 2)
- head(2).prev = newNode(1)
- head = newNode(1)
Output: null <- 1 <-> 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 at front 1 on [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 Front Time & Space Complexity
When to Use Insert at Front
- Adding the most recent action to the front of an undo history
- Pushing onto a deque implemented with a doubly linked list
- Maintaining a most-recently-used list for caching
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.