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.
A1Inspect node links
| Node | Value | Next |
|---|---|---|
| A1 | 2 | A2 |
| A2 | 6 | A3 |
| A3 | 8 | null |
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
#include <cstddef>
struct Node {
int val;
Node* next;
Node(int value = 0, Node* link = nullptr)
: val(value), next(link) {}
};
Node* insert_at(Node* head, int index, int value) {
if (index < 0) return head;
Node dummy(0, head);
Node* prev = &dummy;
for (int i = 0; i < index; ++i) {
if (!prev->next) return head;
prev = prev->next;
}
prev->next = new Node(value, prev->next);
return dummy.next;
}
Node* delete_at(Node* head, int index) {
if (index < 0) return head;
Node dummy(0, head);
Node* prev = &dummy;
for (int i = 0; i < index; ++i) {
if (!prev->next) return head;
prev = prev->next;
}
if (prev->next) {
Node* removed = prev->next;
prev->next = removed->next;
delete removed;
}
return dummy.next;
}