DEV Community

tartope
tartope

Posted on

Singly Linked List Series: Creating get() and set() methods with JavaScript

One can create a number of methods to manipulate a Singly Linked List. Today, I will do my best to share what I understand about creating get() and set() methods. A get() method receives an index parameter and retrieves a node at that particular index. Since Singly Linked Lists are not indexed like arrays, one must create a counter to keep track of "indexes." Let's start with a visualization for creating this method:

Drawing that shows how to build a get method

Edge case: if the index is a negative number or greater than or equal to the length of the list, you can return undefined because that index does not exist. Otherwise, follow the steps above.

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

Code that shows how to build a get method

A set() method changes the value of a particular node. This method accepts index and value parameters. The visualization looks like this:

Drawing that shows how to build a set method

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

Code that shows how to build a set method

The time complexity of a get() and set() method for a Singly Linked List is O(n) linear time because the number of operations increases as the lists' length increases. As I learn more about these topics, the methods become a bit more complex. Share your comments or corrections if there is anything written above that is incorrect. Next week, I will share what I have learned about creating insert() and remove() methods.

Top comments (0)