← All Foundations

Linked Lists

Foundation drill for this topic

Drill #9 — Insert at position k

Easy Pointer Walk

In plain English: Add a new node at a specific position in a linked list.

In a linked list, insertion is O(1) once you're at the right spot — the cost is in walking there.

Prompt

Insert value val at position k (0-indexed) in a linked list.

Try to write it from scratch before scrolling down.

Solution

class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

def insert_at(head, val, k):
    new = Node(val)
    if k == 0:
        new.next = head
        return new
    cur = head
    for _ in range(k - 1):
        cur = cur.next
    # splice new node in
    new.next = cur.next
    cur.next = new
    return head

# Test: 1->2->3, insert 9 at k=1 => 1->9->2->3
O(k) time · O(1) space

Related Micro Drills

Quick recall drills to reinforce this pattern.

23 Insert at head Pointer Manipulation 10s

Head insertion is O(1) and builds lists in reverse. Core for reverse-linked-list.

new = Node(val)
new.next = head
head = new
20 Traverse to end Pointer Manipulation 10s

Linear traversal is how you access linked list elements. Basis for search and length calculation.

while cur: cur = cur.next
22 Append to tail Pointer Manipulation 10s

Tail insertion requires traversal to end. Know this for list construction problems.

while cur.next:
    cur = cur.next
cur.next = Node(val)
See all drills in Linked Lists →