Now that we’ve found the node that we want to remove from the list (or returned None
if it didn’t exist), it’s time to actually remove the node. This means resetting the pointers around the node.
There are three cases here:
- The node was the head of the list, in which case we can just call
.remove_head()
- The node was the tail of the list, in which case we can just call
.remove_tail()
- The node was somewhere in the middle of the list, in which case we will need to manually change the pointers for its previous and next nodes
Instructions
Still in your .remove_by_value()
method, check if node_to_remove
is the list’s head. If so, call .remove_head()
.
Else if node_to_remove
is the list’s tail, call .remove_tail()
.
Else, we know that the node is somewhere in the middle of the list. To remove it, we will need to reset the pointers for the nodes around it. In an else
block, create:
- A
next_node
node that is equal tonode_to_remove
‘s next node - A
prev_node
node that is equal tonode_to_remove
‘s previous node
Now that we have our nodes, we can remove the pointers to and from node_to_remove
and have next_node
and prev_node
point to each other.
Still in the else
block:
- Set
next_node
‘s previous node toprev_node
- Set
prev_node
‘s next node tonext_node
Finally, outside of the else
block, return node_to_remove
.