DEV Community

tartope
tartope

Posted on

Singly Linked List Series: Creating shift() and unshift() methods with JavaScript

While continuing to learn data structures and algorithms, I want to continue to share my understanding in case others find it helpful. Today, I want to share how to create shift() and unshift() methods. A shift() method removes the first node from the beginning of a Singly Linked List. Here is my visualization for creating a shift() method:

steps to create a shift method

Edge case: you can account for an empty list. If it is not empty, then follow the steps mentioned above. A second edge case is to redefine the head and tail if the list becomes empty after multiple shift() method applications.

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

image of shift method code

An unshift method adds a node to the beginning of a Singly Linked List. Here is my visualization for creating an unshift() method:

steps to create an unshift method
steps to create an unshift method continued

Edge case: you can account for an empty list. If the list is not empty then follow the steps mentioned above.

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

image of unshift method code

The time complexity of shift() and unshift() methods for a Singly Linked List is O(1). No matter the length of the list, it takes the same number of steps to remove from the beginning or add to the beginning of the list.

In the next part of this series, I will share what I have learned about creating a get() method to grab a chosen node, and a set() method to change the value of a chosen node.

Top comments (0)