This week I decided to dive into data structures and I thought I start out with linked list. There are a few different types of Linked List such as Singly linked list, Doubly linked list and Circular linked list. For the scope of this blog we will focus on Singly linked list. So what’s a linked list? In short, a linked list is a linear data structure where the collection of data elements does not have a sequential order like an array. Instead each node in the list has a pointer that points to the next node in the list. It might look like this:
Let’s get started by creating a linked list class and create a few methods that will allow us to read, add and remove from it. Now there a few ways that you can do this.
I will start by creating a class of Node where each node we create will take the data and the pointer. In this case will call the pointer “next” and set the default to null.
Next, let’s create the class of LinkedList which will have a constructor with two properties: head and size.
We will have the head set to null and the size equal to zero by default.
Now that we have that setup let’s start inserting the first node.
Here we create the new node and set it to this.head and increment the size of the linked list by 1.
After this, let’s add a “removeAt” which will remove a node based on the index passed.
We start by checking if the index passed is greater than zero along with if the index is greater than the size. If it is, we just return. Then we set up variables for current previous and count. We set current to the first node.
If the index is the first node, we set this.head to the next value.
Else if the the index passed is not equal to zero we will setup a “while loop” where the count is less than the index. We will increment count by 1 and set the previous value to current and set current to what ever the next value is. Since we are removing, will set the previous.next to current.next and decrease the size by 1.
Now let’s add a way to see what is inside the list. We will add “printListData()”
Here we are setting current to the first node and setting up a “while loop” to console log current. This will log data and next, but if you only want the data you could just console log “current.data”. After we console log we set current to the next node. These are just a few methods to get you started …