FunctionRacerProblemsRace

Insert at an Index

EasyLinked listsPython, JavaScript, TypeScript, Java, C++

Insert a new node holding val so that it ends up at position index (the head is index 0), and return the head. index is between 0 and the length of the list, so index equal to the length adds it at the end. The list is passed in as head.

Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.

Example 1

head [1,2,4]
index 2
val 3
returns [1,2,3,4]

The 3 lands at index 2.

Example 2

head [5]
index 0
val 4
returns [4,5]

Inserting at 0 changes the head.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Linked lists problems