Unlike a singly-linked list, a doubly-linked list node keeps a reference to the previous node in addition to the next node. This allows traversal in both directions of the list, towards the head and the tail.
The operations for the doubly linked list is the same a singly linked list.
In this exercise, implement the following functions for the DoublyLinkedListNode and DoublyLinkedList classes:
DoublyLinkedListNodeconstructor()- Write a method that instantiates the node.
- The node takes
value,previousandnext.
LinkedListconstructor()- Write a method that instantiates the list.
- The instance variables
headandtailshould be set tonull.
prepend(value)- Write a method that inserts the
valueat the beginning of the linked list.
- Write a method that inserts the
append(value)- Write a method that inserts the
valueat the end of the linked list.
- Write a method that inserts the
find(value)- Write a method that returns the
nodethat contains thevalue.
- Write a method that returns the
deleteHead()- Write a method that deletes the first element in the linked list.
deleteTail()- Write a method that deletes the last element in the linked list.
delete(value)- Write a method that deletes the
valuein the linked list.
- Write a method that deletes the
The most important operations are prepend/append for adding data, delete for removing data, and find for retrieving data.
To start, build DoublyLinkedListNode. A doubly linked list node keeps a reference to the previous node in addition to the next node. Then, build the constructor the same way as the singly linked list.
Jest Tip: If you need to filter by the exercise name, press
p. After pressingp, enter the string "Doubly" to filter by doubly linked list tests.
- The
prependmethod inserts the item at the beginning of the list. - Operations:
- Create a new
Node. - Set the current head's previous reference to the new node.
- Set the new node's next to the current
head. - Update
headto point at the new node.
- Create a new
- Take into consideration where this is the first value in the linked list.
- The
appendmethod inserts the item at the end of the list. - Operations:
- Create a new
Node. - Set the current tail's
nextto be the new node. - Set the new node's previous to the current
tail. - Update
tailto point at the new node.
- Create a new
- Take into consideration where this is the first value in the linked list.
- The
findmethod returns the node with the target value. - Traverse the array in the same way as a singly linked list.
- The
deleteHead/Tailmethods are useful utilities methods. - Take into consideration where there is only one node in the linked list.
- The
deletemethod removes the first node with the specified value. - The delete operation for a doubly linked list is significantly simpler due to having a reference to the previous node.
- Utilize
findanddeleteHead/Tailmethods written above to write the method.
