Problem Description
Given the head of a linked list and an integer val, remove all the nodes that have Node.val equal to val, and return the new head of the modified linked list.
Key Insights
- Utilize a dummy node to simplify the removal process, especially if the head or several initial nodes need to be removed.
- Traverse the list using a pointer. For each node, check if its next node has the matching val.
- If a node to be removed is found, adjust the pointer to skip it.
- The algorithm processes each node exactly once, ensuring efficiency.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes in the linked list. Space Complexity: O(1), as no additional data structures are used beyond a few pointers.
Solution
The solution employs an iterative approach with a dummy node preceding the head of the list. This dummy node helps handle edge cases seamlessly, such as when the first node (or several beginning nodes) needs to be removed. By iterating through the list, we check if the next node’s value equals the target value, and if so, we skip it. The list is thus re-linked without the undesired nodes, and the new head (dummy.next) is returned.