DEV Community

tartope
tartope

Posted on

Singly Linked List Series: Creating insert(), remove(), and reverse() methods with JavaScript

I will be wrapping up this Singly Linked List Series by sharing my understanding of creating insert(), remove(), and reverse() methods. Beginning with insert(), this method receives two parameters: index and value. This method adds a node at a specified index with the value passed. It returns true if the node was inserted; otherwise, it returns false. This method uses get(), unshift() and shift(), and push() and pop() methods to support it. See the previous Singly Linked List Series blog posts linked above to get an understanding of creating these methods. Let's start with a visualization for creating this method:

Drawing of insert method

Edge case 1: if the index is a negative number or greater than the length of the list, you can return false because that index is not valid.
Edge case 2: if the index is equal to zero, you can use the unshift() method to place a new node at the beginning of the list.
Edge case 3: if the index is equal to the length of the list, you can use the push() method to place a new node at the end of the list.
If none of the above edge cases apply, you can follow the steps above.

Here is an example of code for an insert() method:

Image of code for an insert method

A remove() method will remove a node from a Singly Linked List at a specific index. This method accepts an index as a parameter. The visualization looks like this:

Drawing of remove method

Edge case 1: if the index is a negative number or greater than or equal to the length, you can return undefined because that index is not valid.
Edge case 2: if the index is equal to zero, you can use the shift() method to remove a node from the beginning of the list.
Edge case 3: if the index is equal to the last index in the list, you can use the pop() method to remove a node from the end of the list.
Same as before, if none of the above edge cases apply, you can follow the steps above.

Here is an example of code for a remove() method:

Image of code for a remove method

Lastly, the reverse() method that I will share reverses the list in place. This method takes no parameters. See the steps and visualization below:

Drawing of reverse method

Drawing of reverse method continued

Here is an example of code for a reverse() method:

Image of code for a reverse method

The time complexity of these insert(), remove(), and reverse() methods for a Singly Linked List are O(n) linear time because the number of operations increases as the lists' length increases.

Writing out the steps and drawing the visualizations really helped me better my understanding of creating methods for Singly Linked Lists, and my hope is that this is helpful to someone else, too. However, there is still so much more for me to learn, so feel free to share your comments or corrections if there is anything written above that is incorrect. 🙂

Top comments (0)