Data Structures Doubly Linked Lists Adding a Head Node Exercise

I was wondering if there is a way to illustrate what is going on in this lesson? Is there a recommended python library I can use for data structures?

https://www.codecademy.com/courses/learn-data-structures-and-algorithms-with-python/lessons/doubly-linked-lists-python-lesson/exercises/adding-to-the-head

in particular I had a question about this text in the lesson that speaks to how to add a node to a doubly linked list.

  • Start by checking to see if there is a current head to the list

  • If there is (meaning the list is not empty), then we want to reset the pointers at the head of the list: → at this point have they created a node?

  • Set the current head’s previous node to the new head (Are they talking about the current head node in the linked list, if so, are they saying that they would have the existing head node pointers changed to the new node not yet created?

  • Set the new head’s next node to the current head

  • Update the head property to be the new head

  • Finally, if there isn’t a current tail to the list (meaning the list was empty):

  • Update the tail property to be the new head since that node will be both the head and tail of the list
    so in this case the newly created node would be the only node present and it would have its pointers point to…itself? Am I right in this logic?

For data structures yes. There’s a library for almost all the common ones.
For a doubly linked list in python you can use a deque.

A HUGE caveat is that deques in general are not necessarily supposed to be doubly-linked-lists (maybe for their implementation, but not their behavior) so you should just be aware in case some other language implements it differently.

from collections import deque

my_doubly_linked_list = deque()

https://pythontutor.com/visualize.html#mode=edit

1 Like