Adding values to Linked List

My last blog I discussed arrays and Linked List, the pros and the cons. Linked Link are a data structure and have a very specific way that they are written, they use the class keyword. The Linked List contains a head, tail and length property. It also contains nodes which are a value and pointer to another node or null. Linked List do not have indexes so random access isn’t allowed!

Node set up

First we define the Node class then the constructor which takes in a value. A constructor is a special function of the class that is responsible for initializing the variables of the class. Then val is set to this this.val which is referring to our Node object’s value & would refer to the next node but since we don't have one just yet it’s set to null. First I define a single linked list class and push values is how I will add to the list.

In this block of code, I’ve just defined the head(beginning of list), the tail (last item in list), and the length. The head and tail are initialized with null because it’s currently empty.

To add values into the list, within the singleLinkedList class I’ve created a push method. The push function of course takes in a value, and on line 15, I created a variable to keep track of newly added nodes. Line 16–18 is a conditional check if the list has no head aka empty then create a newNode and set it to this.head and also this.tail meaning the first thing added into the list will be the head and tail. Then lines 19–21 handles the condition that if the list isn’t empty and there’s an existing node with a value, create a new node and set that new node as the tail. For example if the number 3 was already in the linked list and it was the only property there, 3 would be considered the head and the tail. Line 20 points to the node in which the value is 3, then sets the next value to be new value that is pushed in, which lets say will be the number 4. Line 23 increments the list’s length and line 24 returns our list object.

list object is currently empty.
pushed Hello, now list’s length has updated to 1. “Hello” is also the head and tail but next is null until something else is added.
Dolly has been pushed in and now list’s length is 2. The head and tail has 2 different values.
A deeper look into our head node, it’s pointing to the next value in the list which is “Dolly”

I hope this was helpful! Next blog I will discuss getting values from the linked list. Happy Coding !!

The sassy developer