DEV Community

tartope
tartope

Posted on

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

This post will continue to build off of the previous blog on Doubly Linked List methods - linked here. Today I will share how I have learned to create get() and set() methods for a Doubly Linked List. Beginning with get(), this method accepts an index as a parameter and retrieves a node at a chosen position in the list. Since lists are not indexed, a counter will have to be used to find the wanted node. See an illustration below for this method:

First part of drawing for get method
Second part of drawing for get method

Edge case: if the index is less than zero, or greater than or equal to the length of the list, return null. Otherwise, follow the steps listed above.

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

Picture of code for a get method

The method for set() is used to change the value of a node at a chosen position in the list. Set() accepts two parameters - an index to be found, and a value to be updated. Creating this method is a little easier because we can use the get() method created earlier to support this method. Below is an illustration:

Drawing for get method

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

Picture of code for a set method

The time complexity for get() and set() methods in a Doubly Linked List is O(n) linear time because as the lists' length increases so does the number of operations. Please feel free to share comments or corrections if I got anything incorrect. In the next blog I will share what I have learned about creating insert(), remove(), and reverse() methods for Doubly Linked Lists.

Top comments (0)