Linked Lists Singly linked list basics
266. Insert at Position K
You are given head, the first node of a singly linked list, and two integers k and value. Insert a new
node holding value so that it becomes the k-th node of the list. Return the head of the list after the
insertion.
Positions count from 1, so the head is node 1. k = 1 puts the new node in front of the head, and k equal
to the number of nodes plus one puts it after the last node. The nodes already in the list keep their order.
The list may be empty; then k is 1, and the answer is a list of one node.
The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. Your
function gets only the head node, not this array.
Example 1
Input: head = [8, 3, 11, 6], k = 3, value = 20
[8,3,20,11,6]Explanation: The new node holding 20 becomes the third node. The nodes 8 and 3 stay in front of it, and 11 and 6 now follow it.
Example 2
Input: head = [5, -4, 9], k = 1, value = -7
[-7,5,-4,9]Explanation: With k = 1 the new node goes in front of 5 and becomes the new head.
Example 3
Input: head = [0, -6], k = 3, value = 4
[0,-6,4]Explanation: The list has two nodes, so k = 3 is one past the last node. The new node goes after -6 and becomes the
new last node.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 105-109 ≤ Node.val, value ≤ 1091 ≤ k ≤ number of nodes + 1
Clarifying questions
What you would ask an interviewer before writing any code.