Quick actions

cmd+k|ctrl+k

Navigation

Languages

Doubly LinkedList in JavaScript

Snippet info

Language

JavaScript

Visibility

public

Author

patrykstachowiak

Created

2025-03-07T21:16:25.607633Z

Updated

2025-03-07T21:35:19.240508Z

class DoublyLinkedList {
    constructor(value) {
        this.head = new Node(value);
        this.tail = this.head;
        this.length = 1;
    }
    
    append(value) {
        const newNode = new Node(value);
        newNode.prev = this.tail;
        this.tail.next = newNode;
        this.tail = newNode;
        this.length++;

        return this;
    }
    
    prepend(value) {
        const newNode = new Node(value);
        newNode.next = this.head;
        this.head.prev = newNode;
        this.head = newNode;
        this.length++;
        return this;
    }
    
    printList() {
        const array = [];
        let currentNode = this.head;
        while (currentNode !== null) {
            array.push(currentNode.value);
            currentNode = currentNode.next;
        }
        return array;
    }
    
    insert(index, value) {
        if (index >= this.length) {
            return this.append(value);
        }

        const newNode = new Node(value);
        const leaderNode = this.traverseToIndex(index-1);
        const followingNode = leaderNode.next;
        newNode.next = followingNode;
        followingNode.prev = newNode;
        newNode.prev = leaderNode;
        leaderNode.next = newNode;
        this.length++;
        return this;
    }
    
    traverseToIndex(index) {
        let currentNode = this.head;
        for (let i=0; i<index; i++)
        {
            currentNode = currentNode.next;
        }
        return currentNode;
    }
    
    remove(index) {
        if (index >= this.length) {
            console.log("Index doesn't exist");
            return;
        }
        const leaderNode = this.traverseToIndex(index-1);
        const nodeToRemove = leaderNode.next;
        leaderNode.next = nodeToRemove.next;
        this.length--;
    }
}

class Node {
    constructor(value) {
        this.value = value,
        this.next = null,
        this.prev = null
    }
}

const myLinkedList = new DoublyLinkedList(10);
myLinkedList.append(5);
myLinkedList.append(16);
myLinkedList.prepend(1);
console.log(myLinkedList);
console.log(myLinkedList.printList());
myLinkedList.insert(1,333);
console.log(myLinkedList.printList());
myLinkedList.remove(2);
console.log(myLinkedList.printList());
INFO