How to Implement Linked List in JavaScript: Simple Guide
To implement a linked list in JavaScript, create a
Node class to hold data and a reference to the next node, then build a LinkedList class to manage nodes with methods like append and print. This structure allows you to store and traverse data in a chain-like way.Syntax
A linked list uses two main parts: a Node that stores data and a pointer to the next node, and a LinkedList class that manages these nodes.
Node: Holdsvalueandnextpointer.LinkedList: Has aheadto start the list and methods to add or display nodes.
javascript
class Node { constructor(value) { this.value = value; this.next = null; } } class LinkedList { constructor() { this.head = null; } 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; } print() { let current = this.head; let result = ''; while (current) { result += current.value + ' -> '; current = current.next; } result += 'null'; console.log(result); } }
Example
This example shows how to create a linked list, add three values, and print the list to see the order of nodes.
javascript
class Node { constructor(value) { this.value = value; this.next = null; } } class LinkedList { constructor() { this.head = null; } 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; } print() { let current = this.head; let result = ''; while (current) { result += current.value + ' -> '; current = current.next; } result += 'null'; console.log(result); } } const list = new LinkedList(); list.append(10); list.append(20); list.append(30); list.print();
Output
10 -> 20 -> 30 -> null
Common Pitfalls
Common mistakes include:
- Not setting
nexttonullin new nodes, causing unexpected links. - Forgetting to update the
nextpointer when adding nodes, which breaks the chain. - Trying to traverse the list without checking if the current node is
null, causing errors.
Always carefully update pointers and check for null to avoid bugs.
javascript
class Node { constructor(value) { this.value = value; // Missing this.next = null; causes bugs } } // Correct way: class NodeCorrect { constructor(value) { this.value = value; this.next = null; } }
Quick Reference
- Node: Stores data and pointer to next node.
- LinkedList: Manages nodes with
headand methods likeappend. - append(value): Adds new node at the end.
- print(): Shows all node values in order.
Key Takeaways
A linked list uses nodes with a value and a pointer to the next node.
Always initialize the next pointer to null in new nodes to avoid bugs.
Use a LinkedList class to manage nodes and provide methods like append and print.
Traverse the list by following next pointers until you reach null.
Carefully update pointers when adding or removing nodes to keep the list intact.