Node Class for a Linked List with Object Oriented Python

When you come to study Data Structures such as Stacks, Queues, Linked Lists and Binary Trees for A Level Computer Science, you will often make use of Object Oriented Programming. That is a bit of a double whammy if you are not yet very confident with OOP, and it can seem a bit overwhelming.

I’ve made a video which will help you to get started on both these topics. All of the data structures mentioned above make use of a Node class which has two propertiesdata and next. The data part can be thought of the “cargo” and is simply the information we wish to store in our node. The next property is a reference to the node we wish our current nose to point to. It is set to None by default. It is by connecting nodes in various ways that we can create the different data structures. Please note that this “linked list based” approach is not the only one that can be used, but it is very common and studying it will serve you well in your exam.

I have provided the code from the video for you convenience. As usual, you should type it into your favourite editor and run it, without copy-pasting. Then change some things, break it, fix it make it your own.

Let me know how you get on in the comments if you wish.

Python listing for a Node Class for A Level Computer Science

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None


def print_list(node):
    current = node
    while current is not None:
        print(current.data, end=" ")
        current = current.next
    print()


node1 = Node("A")
print(node1.data)

# A -> Ø


node2 = Node("B")
node3 = Node("C")
node1.next = node2
node2.next = node3

print_list(node1)

# A -> B -> C -> Ø

Sharing is caring!

Leave a Reply

Your email address will not be published. Required fields are marked *