Now that we have a basic implementation of a linked list, let's expand its functionality with additional methods for adding to, removing from, traversing, and reversing the list.
Add a new method prepend to add a node to the beginning of the list:
Add a method reverse to reverse the order of the nodes in the list:
javascript
functioncreateLinkedList() {
// ... previous code ...// Add a reverse method to the linked listreverse: function () {
// Initialize the previousNode variable as nulllet previousNode = null;
// Set the currentNode variable to the head of the linked listlet currentNode = this.head;
// Iterate through the linked list until currentNode becomes nullwhile (currentNode) {
// Store the next node in the list in the variable nextNodeconst nextNode = currentNode.next;
// Set the currentNode's next pointer to point to the previous node
currentNode.next = previousNode;
// Move the previousNode pointer to the current node
previousNode = currentNode;
// Move the currentNode pointer to the next node
currentNode = nextNode;
}
// Update the head of the linked list to be the previousNode (the new head)this.head = previousNode;
},
// ... remaining code ...
}
Now, let's use the new methods with our linked list:
In this follow-up tutorial, we added new methods to our linked list implementation. The prepend method adds a node to the beginning of the list, the remove method deletes a node with the specified data, the find method searches for a node with the specified data and returns it, and the reverse method reverses the order of the nodes in the list.
Check out the previous tutorial on linked lists here.