Learn
Since doubly linked lists have a tail property, we don’t have to iterate through the entire list to add to the tail like we did with a singly linked list. The new method will mirror what we did in our .add_to_head()
method:
- Start by checking to see if there is a current tail to the list
- If there is (meaning the list is not empty), then we want to reset the pointers at the tail of the list:
- Set the current tail’s next node to the new tail
- Set the new tail’s previous node to the current tail
- Update the tail property to be the new tail
- Finally, if there isn’t a current head to the list (meaning the list was empty):
- Update the head property to be the new tail since that node will be both the head and tail
Instructions
1.
Define an .add_to_tail()
method that takes self
and new_value
as parameters.
Inside, create:
- A
new_tail
Node
that takesnew_value
as a parameter - A
current_tail
Node
that’s set to the list’s tail
2.
If there is a current tail to the list:
- Set the current tail’s next node to
new_tail
- Set
new_tail
‘s previous node to the current tail
3.
Outside your if
statement, set the list’s tail to the new_tail
.
4.
Lastly, if the list doesn’t have a head, set the list’s head to the new tail.
Sign up to start coding
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.