Insert a Node in a Doubly Linked List

Implement insertDLL

Given the head of a doubly linked list, a value, and a 0-indexed position, insert a new node holding that value at that position and return the new head. Position 0 means the new node becomes the head; a position equal to the list's current length means it becomes the new tail. Splicing a node into the middle only ever touches the handful of pointers right around the insertion point — everything else in the list stays exactly as it was. In a singly linked list that means redirecting two next pointers; in a doubly linked list, the matching prev pointers on both sides of the new node get redirected the same way, so the list can still be walked backward through the new node just as easily as forward.

Example 1:

Input: head = [2,5,7,9], val = 6, position = 2

Output: [2,5,6,7,9]

Example 2:

Input: head = [1,2,3], val = 0, position = 0

Output: [0,1,2,3]

Example 3:

Input: head = [], val = 5, position = 0

Output: [5]

+ 4 hidden test cases run on Submit.

Constraints:

  • 0 ≤ number of nodes in head ≤ 200
  • -1000 ≤ node value, val ≤ 1000
  • 0 ≤ position ≤ length of head — position is 0-indexed, so position 0 means the new head and position length means the new tail
  • This platform's judge reads back only the forward (next) traversal — a real doubly linked implementation also relinks .prev in both directions around the new node

head =

[2, 5, 7, 9]

val =

6

position =

2