Mastering Linked Lists in Python. Understanding the Singly Linked List... | by Sadrach Pierre, Ph.D. | Towards Data Science

Linked lists are important data structures in computer science. A linked list is a linear collection of nodes, where each node contains a data value and a reference to the next node in the list. In this post, we will walk through an example of building a singly linked list corresponding to a music playlist.
Let’s get started!
First, we will define a class called ‘SongNode’. In the argument of the ‘__init__’ method, we will initialize attributes ‘current_song’ and ‘next_song’ as ‘None’:
class SongNode:    def __init__(self, current_song=None, next_song = None):
Next we define the class attributes, ‘current_song’ and ‘next_song’:
class SongNode:    def __init__(self, current_song=None, next_song = None):        self.current_song = current_song        self.next_song = next_song
Now, let’s write a class that will allow us to build our linked song list. Let’s call this class ‘SongList’:
class SongList:    def __init__(self):          self.head = None
We will use the ‘SongList’ class, which will contain a reference to the ‘SongNode’ type, to initialize our song list object. Let’s write an instance of our song list class and print the result:
if __name__=='__main__':    #initialize linked list object    linkedlist = SongList()    print(linkedlist)
Now let’s build a linked list of songs for our playlist. Let’s select the top 3 songs of all time by The Beatles according to Entertainment Weekly. To start let’s define the value of each node. (Note: The ‘...’ corresponds to omitted code):
if __name__=='__main__':    ...     #assign values to nodes     linkedlist.head = SongNode("A Hard Day's Night")    second = SongNode('A Day in the Life')    third = SongNode("Strawberry Fields Forever")
Now let’s define the ‘next song’ value of the head node (the first song):
if __name__=='__main__':    ...    #link nodes    linkedlist.head.next_song = second
Then we define the ‘next song’ value of the second node:
if __name__=='__main__':    ...    second.next_song = third
Next, let’s define a simple function that will allow us to traverse our linked song list. In a while loop we’ll print the value of the current song and redefine the current value as the next song until it reaches the tail of the linked list, which points to null:
class SongList:       ...    def printSongs(self):         value = self.head         while (value):             print(value.current_song)             value = value.next_song
Next, let’s print our list of songs:
if __name__=='__main__':    ...    linkedlist.printSongs()
Next, let’s define a function that allows us to insert a song at the end of our linked list. The function will take the parameter ‘new_song’. The function first checks if the head of the linked list is ‘None’. If it is, the head takes the value of new song:
def NewSong(self, new_song):        NewSongNode = SongNode(new_song)        if self.head is None:            self.head = NewSongNode
Next, the variable ‘last’ is defined as the head node and in a while loop we iterate over the linked objects until we get to the song node that points to null. The ‘next song’ value of the ‘last’ node is then defined as the new song node:
def newSong(self, new_song):    NewSongNode = SongNode(new_song)    if self.head is None:        self.head = NewSongNode    last = self.head    while(last.next_song):        last = last.next_song    last.next_song=NewSongNode
Now, let’s add two new songs “She Loves You” and “Something” and print our list of songs:
if __name__=='__main__':    ...    linkedlist.newSong("She Loves You")    linkedlist.newSong("Something")    linkedlist.printSongs()
I’ll stop here but I encourage you to play around with the code yourself. Specifically, you may want to try defining a function in the ‘SongList’ class that allow you to search for a node. You can also try defining a method that allows you to delete a node.
To summarize, in this post we discussed how to create a linked list corresponding to a playlist of songs. We showed how to define song nodes using the ‘SongNode’ class and how to link ‘SongNode’ objects using the ‘SongList’ class. We also showed how to add additional song nodes to the end of our linked list. I hope you found this post useful/interesting. The code from this post is available on GitHub. Thank you for reading!