Creating the LinkedList class
Now that you understand what a linked list is, let's start implementing our data structure. We are going to create our own class to represent a linked list. The source code for this chapter is available inside the src/06-linked-list
folder. We will start by creating the linked-list.js
file which will contain our class that represents our data structure as well the node needed to store the data and the pointer.
To start, we define a LinkedListNode
class, which represents each element (or node) within our linked list. Each node holds the data
we want to store, along with a reference (next
) pointing to the subsequent node:
class LinkedListNode {
constructor(data, next = null) {
this.data = data;
this.next = next;
}
}
By default, a newly created node's next
pointer is initialized to null
. However, the constructor also allows you to specify the next node if it is known beforehand, proving beneficial in certain scenarios.
Next, we...