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 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. 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

  1. Create a new node with the desired value.
  2. Set newNode.next to the current head.
  3. If the list is not empty, set head.prev to newNode.
  4. Update head to newNode; newNode.prev stays null.

Insert at Front Worked Example

Input: Insert 1 at front of null <- 2 <-> 3 -> null

  1. newNode(1).next = head (node 2)
  2. head(2).prev = newNode(1)
  3. head = newNode(1)

Output: null <- 1 <-> 2 <-> 3 -> null

Try your own input
Doubly LL: Introduction
Like a linked list, but every node keeps a pointer to both the previous and the next node, so you can walk it in either direction.
head
17
prev · next
30
prev · next
43
prev · next
56
prev · next
tail
69
prev · next
Active node next pointer prev pointer
Doubly LL: Introduction
Press ▶ Run to watch it step by step.
Python · Doubly Linked List in Code
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]
Input: Insert 1 at front of null <- 2 <-> 3 -> null

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

TimeO(1)
SpaceO(1)

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.