Insertion at doubly linked list

easy

Given the head of a doubly linked list, a 0-based position p, and an integer x, insert a new node holding the value x immediately after the p-th node, then return the head of the updated list.

A doubly linked list node carries a value plus two links — prev (to the node before it) and next (to the node after it). Inserting in the middle means re-wiring those links so the newcomer is stitched in from both sides.

The position p is guaranteed to be valid, i.e. 0 <= p < size of the list.

Hints

You are only adding one node — how much of the existing list actually needs to change?
Land on the node at index p first. The new node goes between it and whatever currently follows it.
It is a four-pointer handshake: new.next, new.prev, the successor's prev, and curr.next — set them in an order that does not lose the old successor.

Common doubts

It is 0-based. Position p refers to the node reached after p steps from the head, and the new node is inserted immediately after it.
Then curr.next is null and the new node becomes the tail — its next stays null and it simply hangs off the end.
In a doubly linked list every link is two-way. If you only fix the forward links, the list reads correctly going forward but is broken going backward, which shows up the moment something walks prev.

Interview follow-ups

Insert after the (p-1)-th node, or handle p = 0 as a special head-insert by pointing the new node's next at head and updating head's prev.
Drop every prev assignment — you only maintain next. Insertion is the same walk-then-splice, just half the pointers.

Fun facts

  • The whole trick is constant work — insertion into a linked list is O(1) once you are standing at the right spot; all the cost is in getting there.
  • This same four-pointer handshake powers the doubly linked list at the heart of an LRU cache, where nodes are spliced in and out of a usage list on every access.

Asked at

AmazonMicrosoftAdobeGoogle
Frequently Sometimes Occasionally
Example 1
Input: list = 2 <-> 4 <-> 5, p = 2, x = 6
Output: 2 <-> 4 <-> 5 <-> 6
The node at index 2 is `5`. Insert `6` right after it, so `6` becomes the new tail.
Example 2
Input: list = 1 <-> 2 <-> 3 <-> 4, p = 0, x = 44
Output: 1 <-> 44 <-> 2 <-> 3 <-> 4
The node at index 0 is `1`. Insert `44` right after it, between `1` and `2`.
Constraints

- 1 <= list size <= 10^4 - 0 <= p < list size - 0 <= x <= 10^4 - 0 <= node value <= 10^4

Solve this problem →