Learn

The doubly linked list’s tail property allows us to remove the tail just as easily as we could remove the head. In fact, like with the .add_to_head() and .add_to_tail() methods, the .remove_tail() method will closely mirror the .remove_head() method:

  • Start by checking if there’s a current tail to the list.
    • If there isn’t, The list is empty, so there’s nothing to remove, and the method ends
  • Otherwise, update the list’s tail to be the current tail’s previous node
  • If the updated tail is not None (meaning the list had more than one element when we started):
    • Set the tail’s next node to None since there should be no node after the tail of the list
  • If the removed tail was also the head of the list (meaning there was only one element in the list):
    • Call .remove_head() to make the necessary changes to the head of the list
  • Finally, return the old tail’s data

Instructions

1.

Define a .remove_tail() method that only has self as a parameter. Inside, create a removed_tail variable and set it to the list’s tail.

2.

Check if removed_tail has no value. If so, that means the list is empty and there’s nothing to remove, so return None to end the method.

3.

Outside of your if, set the list’s tail to removed_tail‘s previous node.

If the list still has a tail (meaning that the list isn’t now empty), set the tail’s next node to None, since the tail of the list shouldn’t have a next node.

4.

Check if removed_tail is equal to the list’s head. If so, call the .remove_head() method.

5.

Finally, return removed_tail‘s value.

Sign up to start coding

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?