Linear Linked List – Insert Element Beginning using Python

What’s up friends?! Hope your week has been great as always, the weather here has been quite chilly and then hot at different days, so I’ve been taking advantage of it and go hiking quite a bit to clear up my head.

Today, I want to take a moment to introduce data structures. Data structures is one of my favorite topics ever, and in my personal opinion, possibly one of the most important courses of computer science in general, as it provides the foundation for later on. Well, WHAT IS DATA STRUCTURE? Data structure essentially is a way of organizing data for the machine to work efficiently, and you have seen it before, such as array! As such, I want to talk about linear linked list because I am positive colleges would definitely throw these at you, and you definitely are going to spend hours and hours on data structures!

I am going to use a screenshot from GeeksforGeeks to properly demonstrate. Essentially, a linear linked list would definitely has a head node (as shown above), and a tail node (for this example, we are not going to use a tail node), and each node would have a way to point to the next node, creating a linked list (think of a chain). The way you know that a linked list is at the end is the end node would point to NULL.

What we’re going to do today is we are going to insert a node, but only insert at the beginning, we want to dip our toes in, okay?

First, I want to set up the Node class.

# this import is optional, I am using this because I want
# to write the code to generate a random list of linked list
from random import randint

class Node:
    # initializing the node itself
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

Next, I want to set up the LinkedList class. Keep in mind, the process that I’m doing right now is usually standard.

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

    # insert node at the beginning of the list
    # as you can see, we are using pointers to manipulate
    # the data, assigning new node to temp, setting next node to 
    # previous head node, and set up the new head node
    def addBeginning(self, newData):
        temp = Node(newData)
        temp.next = self.head
        self.head = temp

    # generating a random list
    def randomList(self, limit=5):
        
        i = 0
        while i < limit:
            value = randint(0, 20)
            self.addBeginning(value)
            i += 1

        self.display()

    # traversing and display linked list
    def display(self):
        # temp points to head node
        temp = self.head

        # quit the loop of NULL
        while temp.next != None:
            print(temp.data, end=" ")
            temp = temp.next

And the last step! You already guessed it. It is to test out the program!

</pre><pre>myList = LinkedList()
limit = randint(5, 10)
print("*" * 40)
print("Original list: ", end="")
myList.randomList(limit)
print()

value = int(input("Enter your value to add at beginning of list: "))
myList.addBeginning(value)
print("New list: ", end="")
myList.display()
print()

Feel free to tweak the code! Of course, that’s the whole point of this tutorial, I would like to see y’all come up with different answers to this. Like I said, data structures is one of my favorite topics to talk about, so I will definitely bring more content upon this subject in the future. Take care and stay healthy!