Course contentsShow
← Java
Lesson 1027 of 2,87024. List ImplementationsFree lesson

Removing Elements by Value

Sequential traversal to find matching element, then unlinking by updating surrounding nodes' pointers.

Removing Elements by Value

You'll learn how to remove a node from a linked list when you know its value but not its position.

When you want to remove an element from a LinkedList by its value (not its index), the list must walk through its chain of nodes one by one, searching for a match. Once found, the node is unlinked by updating the surrounding nodes' pointers to skip over it.

How It Works

Unlike removing by index where you know exactly where to go, removing by value requires a sequential search. Starting at the head, the list examines each node's value until it finds one that matches (using .equals()).

The unlinking process involves three pointer updates:

  1. If it's the first node: update head to point to the second node
  2. If it's the last node: update tail to point to the second-to-last node, and set that node's next to null
  3. If it's in the middle: update the previous node's next to skip over the matched node, pointing directly to the matched node's next

The Analogy

Imagine a chain of paper clips. To remove a specific red clip, you must slide your fingers along the chain until you spot it. Once found, you unhook it by connecting the clips before and after it directly to each other. The red clip is now isolated and can be discarded.

Why It Matters

The remove(Object o) method in LinkedList uses this approach. It's an O(n) operation because you must traverse potentially the entire list to find the value. If the element doesn't exist, you've walked the entire chain for nothing.

Key Takeaway: Removing by value in a linked list requires sequential traversal to locate the matching node, followed by pointer surgery to unlink it from the chain—a fundamentally O(n) operation.