Home/dsa/Linked List Patterns/Remove Linked List Elements

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 -> 2
Easy

Examples

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)
java
public ListNode removeElements(ListNode head, int val) {
    ListNode dummy = new ListNode(0, head), curr = dummy;
    while (curr.next != null) {
        if (curr.next.val == val) curr.next = curr.next.next;
        else curr = curr.next;
    }
    return dummy.next;
}
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).

  1. head=1, next=remove(6->2, 6).
  2. head=6, next=remove(2, 6).
  3. head=2, next=remove(null, 6) returns null.
  4. 2.val != 6, returns 2.
  5. 6.val == 6, returns remove(2, 6) which is 2.
  6. 1.next = 2, returns 1.
java
public ListNode removeElements(ListNode head, int val) {
    if (head == null) return null;
    head.next = removeElements(head.next, val);
    return head.val == val ? head.next : head;
}