sagelearnai

Remove Linked List Elements

Difficulty: Easy · Pattern: Linked List · LeetCode #203

Remove all nodes whose value equals val and return the new head.

Examples

text
1 → 2 → 6 → 3 → 4 → 5 → 6, val = 6  →  1 → 2 → 3 → 4 → 5
7 → 7 → 7 → 7, val = 7              →  (empty)

Hints

  1. The head itself may need removing. A dummy node avoids special cases.

Approach

Attach a dummy before the head. With cur = dummy, if cur.next.val == val, bypass it; otherwise advance. Return dummy.next. O(n).

Complexity

Time: O(n). Space: O(1).

Python solution
def removeElements(head, val):
    dummy = ListNode(0, head)
    cur = dummy
    while cur.next:
        if cur.next.val == val:
            cur.next = cur.next.next
        else:
            cur = cur.next
    return dummy.next
JavaScript solution
function removeElements(head, val) {
  const dummy = new ListNode(0, head); let cur = dummy;
  while (cur.next) { if (cur.next.val === val) cur.next = cur.next.next; else cur = cur.next; }
  return dummy.next;
}