← Linked Lists

Drill #10 — Delete node at position k

Easy Pointer Walk Linked Lists

In plain English: Remove the node at a specific position from a linked list.

Deletion is pointer surgery: make the previous node skip over the target by pointing to target.next.

Prompt

Delete the node at position k (0-indexed) in a linked list.

Try to write it from scratch before scrolling down.

Solution

def delete_at(head, k):
    if k == 0:
        return head.next
    cur = head
    for _ in range(k - 1):
        cur = cur.next
    cur.next = cur.next.next  # skip over target node
    return head

# Test: 1->2->3->4, delete k=2 => 1->2->4
O(k) time · O(1) space

Related Micro Drills

← Drill #9 Drill #11 →