oneby7

Linked Lists Singly linked list basics

265. Insert at the Tail

Medium

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

5-38
head
5-3829
output

Input: head = [5, -3, 8], values = [2, 9]

Output: [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

4-16

Input: head = [], values = [4, -1, 6]

Output: [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

7
head
70-6
output

Input: head = [7], values = [0, -6]

Output: [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.

head = [1, 2], values = [3, 4, 5]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • 1 ≤ values.length ≤ 105
  • -109 ≤ Node.val, values[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.