How to Implement a Linked List?

By Prajwal Haniya

Techletter #33 | May 29, 2023

Below is the code for linked list implementation in JavaScript. You can review the code and comments to understand it’s implementation.

class Node {
    constructor(data) {
        // The data stored in the node
        this.data = data;
        // Reference to the next node in the linked list
        this.next = null;
    }
}

class LinkedList {
    constructor() {
    // initially head has null
        this.head = null;
    }

    isEmpty() {
        // returns boolean true or false
        return this.head === null;
    }

    insertAtHead(data) {
        const newNode = new Node(data);
        newNode.next = this.head;
        // initialise head with the new node that is created
        this.head = newNode;
    }

    insertAtTail(data) {
        const newNode = new Node(data);
        // Check list is empty
        if (this.isEmpty()) {
            this.head = newNode;
        }
        
        let current = this.head;
        // loop through the list
        while(current.next !== null) {
            current = current.next;
        }
        // if you encounter the node with .next == null add newNode

        current.next = newNode;
    }

    deleteAtHead() {
        // similar to inserting at head
        if (this.isEmpty()) {
            return "No nodes to delete";
        }
        const removedNode = this.head;
        this.head = this.head.next;
        return removedNode.data;
    }

    deleteAtTail() {
        // similar to insert at tail
        if (this.isEmpty()) {
            return "No nodes to delete"
        }
        let currentNode = this.head;
        while(currentNode.next.next !== null) {
            currentNode = currentNode.next;
        }
        currentNode.next = currentNode.next.next; 
        return "Node deleted at tail"
    }
}