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!
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 & this.next 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.
I hope this was helpful! Next blog I will discuss getting values from the linked list. Happy Coding !!