Workspace

Problem workspace

3 day streakD

Insert & Delete by Position

EasyLinked ListsBasics

The challenge

Insert a value at a zero-based position, then delete the node at a zero-based position in the updated list. Each operation returns the new head.

Insertion accepts positions 0…n; deletion accepts 0…n−1. Invalid positions leave the list unchanged.

Example

[2, 6, 8] → insert 4 at 1 → [2, 4, 6, 8] → delete at 2 → [2, 4, 8].

Use the walkthrough below to inspect the input and each state change.

See Insert & delete, step by step

Follow the pointers. Watch each link change.

3 nodes · singly linkedIDs = node identity · ∅ = null
Interior updates: Read the inputIDs label node objects. Equal values can belong to different nodes. Solid arrows are next links; dashed arrows are random links. Node positions stay fixed while arrows change. The pointer strip and node table below give the same state in text.head2A16A28A3∅
CurrentResultYellow arrow: changed next link
headA1
Inspect node links
Each row is a distinct node object. D is the dummy sentinel.
NodeValueNext
A12A2
A26A3
A38null
Step 01 / 8

Read the input

IDs label node objects. Equal values can belong to different nodes. Solid arrows are next links; dashed arrows are random links.

Start from the input head pointers.
View original input

A: 2 (A1) → 6 (A2) → 8 (A3); parameters: {"insertAt":1,"insertValue":4,"deleteAt":2}

Parameter indices are zero-based, except n from the end, which is one-based. Node IDs remain fixed when links change.

Put it into code

A dummy node gives every real node a predecessor, including the head.

Node stores val and next; the random-pointer lesson adds random. C++ uses C++17 or later.

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


def insert_at(head, index, value):
    if index < 0:
        return head
    dummy = Node(next=head)
    prev = dummy
    for _ in range(index):
        if prev.next is None:
            return head
        prev = prev.next
    prev.next = Node(value, prev.next)
    return dummy.next


def delete_at(head, index):
    if index < 0:
        return head
    dummy = Node(next=head)
    prev = dummy
    for _ in range(index):
        if prev.next is None:
            return head
        prev = prev.next
    if prev.next:
        prev.next = prev.next.next
    return dummy.next

A good place to start

Explore a pattern

A little guidance

Start with a pattern, read through a problem, and mark it solved when the idea clicks. Save anything you want to revisit.

New tutorials are added one at a time. Your bookmarks and solved checkmarks stay in this browser.

Explore the roadmap