Linked Lists Singly linked list basics
264. Insert at the Head
You are given head, the first node of a singly linked list, and an array values. Take the values one at a
time, in the order they appear in values, and insert each one at the head: a new node holding the value
becomes the first node, in front of the node that was first before it. Return the head of the list after
every value is inserted.
Each new node goes in front of the one inserted just before it, so the inserted values end up in reverse order, ahead of the nodes the list started with. The nodes already in the list keep their order. If the list is empty, the first new node becomes the whole list.
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 = [9, -4, 12], values = [6, 1]
[1,6,9,-4,12]Explanation: The node for 6 goes in front of 9 and becomes the head. Then the node for 1 goes in front of 6 and becomes the new head.
Example 2
Input: head = [], values = [5, -7, 0]
[0,-7,5]Explanation: The list is empty, so the node for 5 is the whole list at first. The node for -7 goes in front of it, and then the node for 0 goes in front of -7.
Example 3
Input: head = [-3], values = [1000000000]
[1000000000,-3]Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 1051 ≤ values.length ≤ 105-109 ≤ Node.val, values[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.