Data Structures · Visualization
Linked List: Insert at Front
Linked List
Inserting at the front adds a brand-new node before the current head, making the new node the head of the list. Time: O(1). Space: O(1).
Big-O: Lookup O(n); insert/delete at head O(1).
Linked List: Insert at Front
Linked ListInserting at the front adds a brand-new node before the current head, making the new node the head of the list. Because linked lists don't need to shift memory around like arrays do, this is one of the cheapest operations possible.
How Insert at Front Works
- Create a new node with the desired value.
- Point the new node's 'next' to the current head.
- Update head to point to the new node.
Insert at Front Worked Example
Input: Insert 1 at front of head -> 2 -> 3 -> null
- Create newNode(1)
- newNode.next = head (which is node 2)
- head = newNode
Output: head -> 1 -> 2 -> 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 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
- Implementing a stack (push operation) using a linked list
- Adding the most recent item to the front of a history log
- Building a list in reverse order efficiently
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.