oneby7

Linked Lists Singly linked list basics

267. Insert Before the Value X

Medium

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

head
59-392
output
5409-392

Input: head = [5, 9, -3, 9, 2], x = 9, value = 40

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

816
head
-4816
output

Input: head = [8, 1, 6], x = 8, value = -4

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

371
head
371
output

Input: head = [3, 7, 1], x = 5, value = 0

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

head = [2, 6, 4, 6], x = 6, value = 1

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.

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.