Remove Linked List Elements
Master this topic with zero to advance depth.
Remove Linked List Elements
Remove all nodes of the linked list that has Node.val == val.
Visual Representation
List: 1 -> 6 -> 2, val = 6
Result: 1 -> 2Examples
Input: head = [1,2,3,6,4], val = 6
Output: [1,2,3,4]
Approach 1
Level I: Iterative
Intuition
Use a dummy node to handle head removal. Traverse and skip nodes matching val.
⏱ O(N)💾 O(1)
Approach 2
Level II: Recursive
Intuition
Process the rest of the list first. If the current head's value matches the target, return the processed rest; otherwise, link the current head to the processed rest and return the head.
⏱ O(N)💾 O(N) recursion stack
Detailed Dry Run
remove(1->6->2, 6).
- head=1, next=remove(6->2, 6).
- head=6, next=remove(2, 6).
- head=2, next=remove(null, 6) returns null.
- 2.val != 6, returns 2.
- 6.val == 6, returns remove(2, 6) which is 2.
- 1.next = 2, returns 1.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.