Linked Lists Singly linked list basics
265. Insert at the Tail
You are given head, the first node of a singly linked list, and an array values. Add a new node at the
end of the list for each value, in the order the values appear in values. Return the head of the list
after every value is added.
The first new node goes right after the list's last node, the second new node goes after the first, and so on. The nodes already in the list keep their order. If the list is empty, the first new node becomes the 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, -3, 8], values = [2, 9]
[5,-3,8,2,9]Explanation: The last node holds 8. The node for 2 goes after it, and the node for 9 goes after the node for 2.
Example 2
Input: head = [], values = [4, -1, 6]
[4,-1,6]Explanation: The list is empty, so the node for 4 becomes the head. The nodes for -1 and 6 follow it.
Example 3
Input: head = [7], values = [0, -6]
[7,0,-6]Explanation: The only node, 7, is both the head and the last node. The head stays the same, and the new nodes go after it.
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.