JavaScript Data Structures: Linked Lists - Improve Your Technical Blog
Linked lists are a crucial data structure to learn in JavaScript. They allow us to efficiently store and manage data by connecting each item to the next item in the list. Unlike arrays, linked list items do not need to be stored in adjacent memory locations and cannot be randomly accessed using indices.
Since JavaScript does not natively support linked lists, we can create our implementation. To start, let’s create the “Item” class that represents each item in the linked list:
1 | class Item { |
The “Item” class contains two properties: “next” and “value”. “next” is a reference to the next item in the list, and “value” holds the actual value of the item.
Next, we’ll define the “LinkedList” class, which will have two private properties: “head” and “tail”. The “LinkedList” class provides methods for adding items to the list and obtaining the size of the list:
1 | class LinkedList { |
In the above code, the “append” method adds an item to the end of the linked list. If it’s the first item being added, the item becomes both the head and tail of the list. The “size” method iterates through the list and counts the number of items.
Let’s see how we can use the LinkedList class:
1 | const list = new LinkedList(); |
We can also find an item in the list by its value using the “find” method:
1 | class LinkedList { |
To insert an item at a specific position in the linked list, we can use the “insert” method:
1 | class LinkedList { |
Lastly, there is the double-linked list, where each item has a reference to both the next and previous elements.