Learn

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

1.

Still in your .remove_by_value() method, check if node_to_remove is the list’s head. If so, call .remove_head().

2.

Else if node_to_remove is the list’s tail, call .remove_tail().

3.

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 to node_to_remove‘s next node
  • A prev_node node that is equal to node_to_remove‘s previous node
4.

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 to prev_node
  • Set prev_node‘s next node to next_node
5.

Finally, outside of the else block, return node_to_remove.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?