Problem 290189 · easy · Phase 02 Linear Data Structures

Delete the First Occurrence

linked list · deletion · dummy node

Given the head of a singly linked list and a value val, remove the first node whose value equals val and return the head of the resulting list. If no node matches, return the list unchanged.

Examples

Input:  head = 1 -> 2 -> 3 -> 2, val = 2
Output: 1 -> 3 -> 2

Input:  head = 7, val = 7
Output: (empty)

Constraints

  • 0 <= number of nodes <= 10**4
  • Target: O(n) time, O(1) extra space

Goals

  • Unlink a node by rewiring its predecessor
  • Stop after the first match
Starting Python…