2dbi

Remove Linked List Elements

viaLeetCode

Problem Given the head of a linked list and an integer val, remove every node whose value equals val and return the new head.

Input / Output

  • Input: head of singly linked list, int val.
  • Output: new head after removals.

Constraints

  • Up to 10^4 nodes; O(n) time, O(1) space.

Example

  • 1→2→6→3→4→5→6, val = 6 → 1→2→3→4→5.
  • 7→7→7, val = 7 → empty list.

Expected approach

  • Dummy (sentinel) node pointing at head unifies the head-removal case: walk prev from the dummy; if prev.next.val == val, splice it out (prev.next = prev.next.next), else advance. Return dummy.next. Also worth knowing: the recursive one-liner and its O(n) stack cost.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account