Implementing a Singly Linked List in JavaScript: pt. 3

We are finally going to discuss the last two methods, insert/2 and remove/1, that a link list should have.

Let’s talk about insert first.

insert/2 method

We have some sort of value and an index we need to insert that value at. We first check our edge cases. If the index is less than zero or greater than the length of the list, it is not possible to insert the value and therefore we return false. If the index is equal to the length of the list we simply push it on, and coerce the return value of running push/1 to a boolean. Finally, if the length of the list is 0 we can simply add it to the front.

After checking edge cases we can now implement the actual logic. We define a new node, necessary for holding the value and the links between the adjacent values of our new node.

We define a variable called node, which is simply the node that comes before the index where we wish to insert our new value. The oldNode variable is the node that will now come after our new variable. We insert and link the new value into the list and finally increment the length by one in order to account for the new addition.

We return true to signify the operation happened successfully.

Now let’s take a gander at remove.

remove/1

Removing is very similar to inserting. We make the usual edge case checks before implementing our logic.

We then grab the node before the node we wish to remove. This is because in order to remove the item completely from the list, we must remove the connection between the node before it and itself. We simply set the value of the previous node’s next property, to the value of the next property of the node we are removing. After we do this we decrement the length by one to account for the removal and return the removed node.

I will continue to write about data structure in a simple to follow way! My next goal is to tackle stacks and queues.

Full-Stack Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store