Insert at an Index
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
0 <= number of nodes <= 1000 <= index <= number of nodes-100 <= Node.val, val <= 100
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.