oneby7

Linked Lists Singly linked list basics

266. Insert at Position K

Medium

You are given head, the first node of a singly linked list, and two integers k and value. Insert a new node holding value so that it becomes the k-th node of the list. Return the head of the list after the insertion.

Positions count from 1, so the head is node 1. k = 1 puts the new node in front of the head, and k equal to the number of nodes plus one puts it after the last node. The nodes already in the list keep their order. The list may be empty; then k is 1, and the answer is a list of one node.

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
83116
output
8320116

Input: head = [8, 3, 11, 6], k = 3, value = 20

Output: [8,3,20,11,6]

Explanation: The new node holding 20 becomes the third node. The nodes 8 and 3 stay in front of it, and 11 and 6 now follow it.

Example 2

5-49
head
-75-49
output

Input: head = [5, -4, 9], k = 1, value = -7

Output: [-7,5,-4,9]

Explanation: With k = 1 the new node goes in front of 5 and becomes the new head.

Example 3

0-6
head
0-64
output

Input: head = [0, -6], k = 3, value = 4

Output: [0,-6,4]

Explanation: The list has two nodes, so k = 3 is one past the last node. The new node goes after -6 and becomes the new last node.

Check your understanding

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

head = [7, 1, 8, 2], k = 2, value = 5

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val, value ≤ 109
  • 1 ≤ k ≤ number of nodes + 1

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.