oneby7

Linked Lists Singly linked list basics

264. Insert at the Head

Medium

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

9-412
head
169-412
output

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

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

0-75

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

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

-3
head
10⁹-3
output

Input: head = [-3], values = [1000000000]

Output: [1000000000,-3]

Check your understanding

Work out the answer for this input before you write any code.

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

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.