DEV Community

tartope
tartope

Posted on

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

Building off of last week's blog on Doubly Linked List classes, push(), and pop() methods - linked here - today I will be discussing shift() and unshift() methods. Starting with shift(), this method does not take a parameter and removes the first node from the beginning of the list. Here is an illustration of a shift() method:

Drawing of shift method

Edge case: you can account for an empty list, or has only one node. If neither of those cases applies, then follow the steps above.

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

Screen shot of shift method code

The method unshift() adds a node to the beginning of the list. Here is an illustration of this method:

Drawing of unshift method

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:

Screen shot of unshift method code

The time complexity for shift() and unshift() methods for a Doubly Linked List is O(1) constant time. The length of the list does not impact the 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 get() and set() methods for a Doubly Linked List.

Top comments (0)