Insert a Node in a Doubly Linked List
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
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
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Copy to Array, Splice, Rebuild
BruteCopy every value into an array, splice the new value into that array at the target position, then rebuild the list from scratch. Correct, but it discards and reallocates every node instead of relinking the handful of pointers that actually needed to change.
O(n)O(n)1// Node definition used in this problem:
2// class Node {
3// int val;
4// Node next;
5// }
6
7class Solution {
8 public Node insertDLL(Node head, int val, int position) {
9 List<Integer> vals = new ArrayList<>();
10 Node curr = head;
11 while (curr != null) {
12 vals.add(curr.val);
13 curr = curr.next;
14 }
15 vals.add(position, val);
16 Node dummy = new Node(0);
17 Node tail = dummy;
18 for (int v : vals) {
19 tail.next = new Node(v);
20 tail = tail.next;
21 }
22 return dummy.next;
23 }
24}Optimal — Traverse to Position-1, Splice In
OptimalPosition 0 is really just insert-at-the-beginning — handle it the same O(1) way. Otherwise, walk from head to the node just before the target position, then redirect two pointers: the new node's next takes over what curr used to point at, and curr's next is redirected through the new node. In a true doubly linked list, the new node's prev is also pointed back at curr, and curr's old successor has its prev pointed at the new node — the same splice, mirrored in the other direction.
O(n)O(1) extra1// Node definition used in this problem:
2// class Node {
3// int val;
4// Node next;
5// }
6
7class Solution {
8 public Node insertDLL(Node head, int val, int position) {
9 Node newNode = new Node(val);
10 if (position == 0) {
11 newNode.next = head;
12 return newNode;
13 }
14 Node curr = head;
15 for (int i = 0; i < position - 1; i++) {
16 curr = curr.next;
17 }
18 newNode.next = curr.next;
19 curr.next = newNode;
20 return head;
21 }
22}