AlgoViz

Insert node before head in Doubly Linked List

Easy

Wire both directions, then move the head

Problem

Given the head of a doubly linked list and a value, insert a new node with that value before the current head and return the new head, fixing both prev and next links.

In simple words

Hook a new node in front of the head, fixing the back-pointer too.

The idea

Set the new node's next to the old head and the old head's prev back to the new node, then return the new node. Forgetting the backward link leaves a list that walks forwards correctly and breaks when walked in reverse.

The trick

  • Four assignments: newNode.next, newNode.prev, oldHead.prev, and the new head.
  • Guard the empty-list case where there is no old head to point back.

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

2
3
0
1

Step 1 of 2. Here's the example — head = [2, 3], val = 1 Values: 2, 3.

1/2
Optimal
timeO(1)spaceO(1)
1n = Node(val)2n.next = head3if head != null: head.prev = n4head = n5return head

Input

array
[2, 3]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Example

Input:
head = [2, 3], val = 1
Output:
[1, 2, 3]

Practice this problem:GeeksforGeeks(opens in a new tab)

Finished the walkthrough? Add it to your streak.