Delete all occurrences in a doubly linked list

medium

You are given the head of a doubly linked list and an integer key x. Some nodes may hold the value x — one, several, scattered anywhere, or none at all. Delete every node whose value equals x and return the head of the resulting list.

The surviving nodes must keep their original order, and — because this is a doubly linked list — every remaining node's prev and next pointers must be re-stitched so the list is still walkable in both directions. If the old head itself is deleted, the returned head is the first surviving node; if the whole list is deleted, return an empty list.

Hints

You never need a second list — the nodes you keep are already correctly ordered.
When you remove a node, who suddenly needs to hold hands with whom? Think about both its neighbours.
Save the next pointer before you unlink, and treat a missing prev (the head) as its own case: move the head forward.

Common doubts

It has no prev, so instead of patching a left neighbour you advance the head pointer to curr.next. If several leading nodes match, this branch fires repeatedly.
No. Because you always relink curr's actual prev and next, a run of matches unravels one node at a time on its own.
Once curr is unlinked, reading pointers off it is unreliable. Storing nxt = curr.next first guarantees the walk can always advance.

Interview follow-ups

Without a prev pointer you track the previous node manually, or use a dummy head so head-deletions need no special case; you set prev.next = curr.next.
Stop the scan and return as soon as one match is spliced out — an early return turns the same pointer logic into a single-delete.

Fun facts

  • The two-sided splice — join left neighbour to right on both next and prev — is the single reflex behind almost every doubly-linked-list edit.
  • This exact remove-and-advance loop powers LRU caches, where nodes are constantly unlinked from the middle and moved to the front.

Asked at

AmazonMicrosoftAdobeGoogle
Frequently Sometimes Occasionally
Example 1
Input: head = 2<->2<->10<->8<->4<->2<->5<->2, x = 2
Output: 10<->8<->4<->5
Every node holding 2 is removed; the four survivors keep their order and stay linked both ways.
Example 2
Input: head = 9<->1<->3<->4<->5<->1<->8<->4, x = 9
Output: 1<->3<->4<->5<->1<->8<->4
Only the head held 9, so it is unlinked and the second node becomes the new head.
Constraints

- 1 <= number of nodes <= 10^5 - 0 <= node value <= 10^9 - The list is a valid doubly linked list (every prev/next pair is consistent).

Solve this problem →