Delete a Node in a Doubly Linked List
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ number of nodes in head ≤ 200 - ◆
-1000 ≤ node value ≤ 1000 - ◆
0 ≤ position < length of head — position is 0-indexed - ◆
This platform's judge reads back only the forward (next) traversal — a real doubly linked implementation also relinks the removed node's neighbors' .prev pointers
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, Remove, Rebuild
BruteCopy every value into an array, remove the entry at the target position, then rebuild the list from that shortened array. Correct, but it discards and reallocates every remaining node instead of relinking the two pointers around the deleted node.
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 deleteDLL(Node head, 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.remove(position);
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, Bypass the Target Node
OptimalPosition 0 is really just delete-at-the-beginning — handle it the same O(1) way. Otherwise, walk to the node just before the target position, then redirect its next pointer straight past the target node: curr.next = curr.next.next. The target node is never visited or modified — it's simply skipped over. In a true doubly linked list, the node right after the deleted one also has its prev pointed back at curr, the same bypass mirrored backward.
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 deleteDLL(Node head, int position) {
9 if (position == 0) {
10 return head.next;
11 }
12 Node curr = head;
13 for (int i = 0; i < position - 1; i++) {
14 curr = curr.next;
15 }
16 curr.next = curr.next.next;
17 return head;
18 }
19}