Singly Linked List: A Python Implementation

datadeverik

Erik Anderson

Posted on November 22, 2019

Singly Linked List: A Python Implementation

Recently in my computer science course I implemented a singly linked list for an assignement. To solidify the concepts, I'm going to rebuild it in python. And for your benefit, I'm going to write about it.

A singly linked list is composed of nodes, each of which points to another node. The only exception is the last node, which instead points to None. The nodes also contain a value. This can be just about anything, but for this demonstration I'll just use integers.

The first thing to do is define a class.

class SLLNode:
    """
    A node in a singly linked list.
    Attributes:
        value - the value to be stored and displayed, integer
        next - a reference to the next Node in the list
    """
Enter fullscreen mode Exit fullscreen mode

Here I've defined the class and sketched out my plans for it. But I still need to implement it. To do that we need an initialization method. At least, we need the initialization method to do it neatly.

# indented with class SLLNode:
    def __init__(self, value=None, next_node=None):
        self.value = value
        self.next_node = next_node
Enter fullscreen mode Exit fullscreen mode

There's a bit to unpack here, but first let's check and see what it does. We'll do this by using the following code:

node = SLLNode(7, None)
print("Node with value {} and next node {}.".format(node.value, node.next_node))
Enter fullscreen mode Exit fullscreen mode

And the output from that is:

Node with value 7 and next node None.
Enter fullscreen mode Exit fullscreen mode

So what happened?
When I called SLLNode(7, None), it ran the __init__() method with the arguments 7 and None. This stored 7 to the attribute value and None to the attribute next_node.

What do we have so far? We have a way to create a node, and a convenient way to print the key information about that node, which will be helpful for debugging going forward. That's a pretty basic start, but it's where I'll end it for now.
More to come in this series as I build out the list.

The code for this project is available here on GitHub. I'll be updating it gradually as I write this series. I'll be sure to commit at least as often as I post, so you can back up and see that code as it was when I published a given post.

EDIT: The next post is now available here.

πŸ’– πŸ’ͺ πŸ™… 🚩
datadeverik
Erik Anderson

Posted on November 22, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related