![doubly linked list doubly linked list](https://codingee.com/wp-content/uploads/2019/11/doubly-linked-list.png)
![doubly linked list doubly linked list](https://i1.wp.com/simplesnippets.tech/wp-content/uploads/2019/06/doubly-linked-list-diagram.png)
Having a Doubly Linked List can come in handy if you need to traverse the list from the head or the tail. However, there are a few differences to keep in mind. From here, you can add or remove nodes easily using the methods we wrote.Īs you can see from the example above, adding and removing from a Doubly Linked List is similar to that of a Singly Linked List. At the end of the code, we are creating a list and pushing the values 1–5 to the list. In our example, we have the Node class and Doubly Linked List class with our methods for push, pop, shift, and unshift.
#Doubly linked list code
The final code should look something like below. Finally, we will increase the length of the list by one and return the list. If the list is not empty, we will set the next property on the current tail to the new node, set the previous property on the new node to be the current tail, and set the tail property of the list to be the new node. If so, then we will simply set the head and the tail of the list to the new node. We can do this by checking if there is no head, or if the length is equal to 0. There is one edge case that we need to check for which is if the list is empty. The push method will take a value as an argument and we will first create a new node with that value, which we are saving here as newNode. It is similar to building a Singly Linked List class, except we need to keep in mind that each node has both a next and a previous value. In this article, we will handle the basic methods for push, pop, shift, and unshift. We will now add methods to our Doubly Linked List class.