JavaScript Data Structures: Linked List
When we think about storing data in JavaScript, arrays are usually the first choice.
But arrays are not always efficient for operations like inserting or deleting in the middle.
π Thatβs where Linked Lists shine.
π What is a Linked List?
A Linked List is a linear data structure where each element (called a node) points to the next one.
Unlike arrays, linked lists do not store elements in contiguous memory.
- Each node contains:
- The value (data)
- A reference (pointer) to the next node
Example structure:
[head] β [node1] β [node2] β [node3] β null
π Implementing a Linked List in JavaScript
Node class
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
LinkedList class
class LinkedList {
constructor() {
this.head = null;
}
// Insert at the end
append(value) {
const newNode = new Node(value);
if (!this.head) {
this.head = newNode;
return;
}
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
// Insert at the beginning
prepend(value) {
const newNode = new Node(value);
newNode.next = this.head;
this.head = newNode;
}
// Find a node
find(value) {
let current = this.head;
while (current) {
if (current.value === value) return current;
current = current.next;
}
return null;
}
// Delete a node
delete(value) {
if (!this.head) return;
if (this.head.value === value) {
this.head = this.head.next;
return;
}
let current = this.head;
while (current.next && current.next.value !== value) {
current = current.next;
}
if (current.next) {
current.next = current.next.next;
}
}
// Print all values
print() {
let values = [];
let current = this.head;
while (current) {
values.push(current.value);
current = current.next;
}
console.log(values.join(" β "));
}
}
β Example in Action
const list = new LinkedList();
list.append(10);
list.append(20);
list.append(30);
list.prepend(5);
list.print(); // 5 β 10 β 20 β 30
console.log(list.find(20)); // Node { value: 20, next: Node { value: 30, ... } }
list.delete(10);
list.print(); // 5 β 20 β 30
π When to Use Linked Lists
- When frequent insertions/deletions are needed
- When memory needs to be managed dynamically
- When array resizing is too costly
βοΈ Trade-offs
β Pros:
- Efficient insertion/deletion
- Dynamic size
β Cons:
- Slower access (no direct index access like arrays)
- More memory (extra pointer storage)
π― Conclusion
Linked Lists are a fundamental data structure every developer should understand.
Even if arrays are more common in JavaScript, knowing linked lists gives you a deeper understanding of memory, efficiency, and algorithms.
Next time you need flexible insertions or deletions, think beyond arrays β and try a Linked List!
Top comments (0)