Insert at Specific Position
EasyP3Coding
Given the head of a singly linked list, an integer data and a 0-based position, insert a new node holding data so that it ends up at index position. Return the head of the resulting list.
Positions run from 0 (insert at the front) up to the list length (insert at the end). A list node has val and next. The ListNode class is already defined for you.
Example 1
- Input
- head = [1,2,4], data = 3, position = 2
- Output
- [1,2,3,4]
Example 2
- Input
- head = [1,2], data = 0, position = 0
- Output
- [0,1,2]
Example 3
- Input
- head = [], data = 5, position = 0
- Output
- [5]
Constraints
- 0 <= number of nodes <= 1000
- 0 <= position <= number of nodes
- -10^4 <= data, Node.val <= 10^4
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 10. ⌘Enter runs, ⌘⇧Enter submits.