Insertion at a Given Position in a Linked List

easy

You are given the head of a singly linked list, a 1-based position pos, and a value val. Insert a new node holding val at position pos and return the head of the modified list.

After the insertion, the new node occupies the pos-th slot (counting from 1). Everything that was at position pos and beyond simply slides one step to the right; everything before it stays exactly where it was.

Two boundaries are worth naming:

  • pos = 1 means the new value becomes the new head.
  • pos = size + 1 means the new value is appended just past the current last node.

Hints

You never touch the node at position pos directly — which node do you actually need a handle on?
Inserting at position 1 has no predecessor inside the list. Is there a way to give it one?
Put a dummy node before head, walk pos-1 steps, then set new.next = prev.next and prev.next = new.

Common doubts

1-based. Position 1 means the new node becomes the head; position size + 1 appends at the end.
Position 1 has no predecessor inside the list. A dummy node before head gives it one, so a single loop handles every position with no special case.
Yes. Set new.next = prev.next first, then prev.next = new. Reversing them makes the new node point at itself and loses the rest of the list.

Interview follow-ups

Same walk to the predecessor, then a single rewire: prev.next = prev.next.next — after guarding that prev.next exists.
You would also fix the new node's prev pointer and the successor's prev pointer — four links instead of two, but still O(1) at the spot.

Fun facts

  • The dummy (sentinel) node trick shows up in almost every list-mutation problem — insert, delete, merge, partition — because it makes the head stop being a special case.
  • Inserting mid-list is where linked lists beat arrays: no O(n) shifting of later elements, just two pointer writes once you're at the spot.

Asked at

AmazonMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: head = [1, 3], pos = 3, val = 4
Output: 1 -> 3 -> 4
Position 3 is one past the last node, so 4 is appended to the end.
Example 2
Input: head = [1, 2, 9], pos = 2, val = 5
Output: 1 -> 5 -> 2 -> 9
5 is inserted before the node at position 2, landing between 1 and 2.
Constraints

- 1 <= list size <= 10^4 - 1 <= pos <= list size + 1 - 1 <= val <= 10^4

Solve this problem →