In this activity, we're going to be creating the framework for a doubly linked list. A doubly linked list is a linked list where each node keeps track of the node before and after it, so we can traverse the tree both forwards and backwards.
-
For this activity, we will be operating directly on the properties we're storing in the
Node- Create a
Nodeconstructor that keeps track of thevalueof this node, the node to theleftof this node, and the node to therightof this node. - When a
Nodeis initialized, if it is passed a value, store that value within the node. If it isn't passed a value, then initialize thevalueof the node to null. - The
leftandrightof the node should initialize to null.
- Create a
-
Then create a
DoublyLinkedListconstructor that keeps track of theheadandtailof the list.- All values should initialize to null.
-
Add an
insertBeforemethod that takes in a value and a node as arguments. It will create a newNodecontaining the value and insert the new node before the argument node.- If the node being inserted is the first element of the list, it will be both the
headand thetail - If the argument node is the
headof the list, you will have to update theheadto point to the new node. - Remember to update the
leftandrightpointers of both the new node and the argument node.
- If the node being inserted is the first element of the list, it will be both the
-
Add an
insertAftermethod that takes in a value and a node as arguments. It will create a newNodecontaining the value and insert the new node after the argument node.- If the node being inserted is the first element of the list, it will be both the
headand thetail - If the argument node is the
tailof the list, you will have to update thetailto point to the new node. - Remember to update the
leftandrightpointers of both the new node and the argument node.
- If the node being inserted is the first element of the list, it will be both the