Quick actions

cmd+k|ctrl+k

Navigation

Languages

LinkedList in Java Script

Snippet info

Language

JavaScript

Visibility

public

Author

patrykstachowiak

Created

2025-03-07T16:54:30.70174Z

Updated

2025-03-07T21:57:44.382295Z

class LinkedList {
    constructor(value) {
        this.head = new Node(value);
        this.tail = this.head;
        this.length = 1;
    }
    
    append(value) {
        const newNode = new Node(value);
        this.tail.next = newNode;
        this.tail = newNode;
        this.length++;
        return this;
    }
    
    prepend(value) {
        const newNode = new Node(value);
        newNode.next = this.head;
        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);
        let leaderNode = this.traverseToIndex(index-1);
        newNode.next = leaderNode.next;
        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--;
    }
    
    reverse() {
        if (this.length === 1) {
            return this.head;    
        }
        
        let currentNode = this.head;
        let prevNode = null;
        let nextNode = null;
        
        this.tail = currentNode;
        
        while (currentNode != null)
        {
            nextNode = currentNode.next;
            currentNode.next = prevNode;
            prevNode = currentNode;
            currentNode = nextNode;
        }
        this.head = prevNode;
    }
}

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

const myLinkedList = new LinkedList(10);
myLinkedList.append(5);
myLinkedList.append(16);
myLinkedList.prepend(1);

console.log(myLinkedList.printList());
myLinkedList.insert(1,333);
console.log(myLinkedList.printList());
myLinkedList.remove(2);
myLinkedList.reverse();
console.log(myLinkedList.printList());
INFO