In addition to removing the head and the tail of the list, it would also be useful to be able to remove a specific element from anywhere in the list.
Imagine that you have a list of errands to run. You don’t always do your errands in order, so when you finish doing your laundry and want to cross it off, that could be somewhere in the middle of the list. We are going to build a .remove_by_value()
method that will allow you to cross off (remove) that errand no matter where it is in the list.
In order to do this:
- Iterate through the list to find the matching node
- If there is no matching element in the list:
- Return
None
- Return
- If there is a matching node, we will then check to see if it is the head or tail of the list:
- If so, call the corresponding
.remove_head()
or.remove_tail()
method
- If so, call the corresponding
- If not, that means the node was somewhere in the middle of the list. In that case:
- Remove it by resetting the pointers of its previous and next nodes
- Finally, return the node’s value property
Instructions
Define a .remove_by_value()
method that takes self
and value_to_remove
as parameters.
Inside it, create a node_to_remove
node. We don’t know what it is yet, so set it to None
.
Create a current_node
node and set it equal to the list’s head. Then create a while
loop that runs while current_node
isn’t None
.
Inside the loop, update current_node
to be its next node. This is how we will iterate through the list as we look for the matching node.
(If you accidentally create an infinite loop and your code won’t stop running, you can reload the page to stop it.)
Inside the while
loop, but before you updated current_node
to be its next node, create an if
statement that checks if current_node
‘s value
matches the passed in value_to_remove
. If it does, that means we have found the matching node.
Inside the if
:
- Set
node_to_remove
tocurrent_node
break
to leave thewhile
loop, since we don’t need to keep looking through the list
Outside your while
loop, check if node_to_remove
has any value. If it doesn’t, that means there was no matching node in the list, so return None
to end the method.