Insert a Node at a Given Position in a Linked List
Implement insertAtPosition
Given the
head of a singly linked list, an integer val, and a 0-indexed position, insert a new node holding val so that it ends up at index position in the resulting list, and return the head.
position = 0 is exactly the insert-at-the-beginning case, and position equal to the list's current length is exactly the insert-at-the-end case — this problem generalizes both. The optimal solution walks to the node just before the target index and redirects two pointers, without touching any other existing node.
Example 1:
Input: head = [1,2,4], val = 3, position = 2
Output: [1,2,3,4]
Example 2:
Input: head = [5,10,15], val = 1, position = 0
Output: [1,5,10,15]
Example 3:
Input: head = [7,8], val = 9, position = 2
Output: [7,8,9]
+ 5 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ number of nodes in head ≤ 10⁴ - ●
-10⁹ ≤ node value, val ≤ 10⁹ - ●
0 ≤ position ≤ length of head — position is 0-indexed, so position 0 means the new head and position length means the new tail
head =
[1, 2, 4]
val =
3
position =
2