Linked Lists Singly linked list basics
267. Insert Before the Value X
You are given head, the first node of a singly linked list, and two integers x and value. Insert a new
node holding value just before the first node that holds x, and return the head of the list.
If no node holds x, return the list unchanged. When x sits in the head node, the new node becomes the new
head.
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 = [5, 9, -3, 9, 2], x = 9, value = 40
[5,40,9,-3,9,2]Explanation: The first node holding 9 is the second one. The new node holding 40 goes between 5 and that 9. The later 9 is left alone.
Example 2
Input: head = [8, 1, 6], x = 8, value = -4
[-4,8,1,6]Explanation: The head holds 8, so the new node goes in front of it and becomes the new head.
Example 3
Input: head = [3, 7, 1], x = 5, value = 0
[3,7,1]Explanation: No node holds 5, so the list comes back as it was.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109-109 ≤ x, value ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.