Skip to main content
Back to problems
#203
Easy Algorithms

Remove linked list elements

Linked List Recursion
53.9% acceptance
Jan 12, 2026
8992
290
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn remove_elements(head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
    let mut dummy = Box::new(ListNode::new(0));
    dummy.next = head;
    let mut current = &mut dummy;
    
    while let Some(ref mut next_node) = current.next {
      if next_node.val == val {
        current.next = next_node.next.take();
      } else {
        current = current.next.as_mut().unwrap();
      }
    }
    dummy.next
  }
}