Key Concepts

Review core concepts you need to learn to master this subject

Adding to the Tail

def add_to_tail(self, new_value): new_tail = Node(new_value) current_tail = self.tail_node if current_tail != None: current_tail.set_next_node(new_tail) new_tail.set_prev_node(current_tail) self.tail_node = new_tail if self.head_node == None: self.head_node = new_tail

A Python DoublyLinkedList class can implement an .add_to_tail() instance method for adding new data to the tail of the list. .add_to_tail() takes a single new_value argument. It uses new_value to create a new Node which it adds to the tail of the list.

Doubly Linked Lists: Python
Lesson 1 of 1
  1. 1
    Now that we’ve learned about doubly linked lists, let’s implement one in Python. As a reminder, a doubly linked list is a sequential chain of nodes, just like a singly linked list. The nodes we…
  2. 2
    In a singly linked list, we can add to the head of the list by checking to see if it already has a head. We then either set the new node as the head (if there was no head) or update the head proper…
  3. 3
    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 …
  4. 4
    Due to the added tail property, removing the head of the list in a doubly linked list is a little more complicated than doing so in a singly linked list: - Start by checking if there’s a current he…
  5. 5
    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() …
  6. 6
    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 ru…
  7. 7
    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. …
  8. 8
    You finished your DoublyLinkedList class! Now we’re going to use that class to model a subway line. A doubly linked list is a great data structure to use to model a subway, as both have a first and…
  9. 9
    Congratulations, you have created a doubly linked list class in Python! We did this by: - Using our Node class to hold the value and links between nodes - Implementing a DoublyLinkedList class to …

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo