Quick actions

cmd+k|ctrl+k

Navigation

Languages

LinkedList

Snippet info

Language

JavaScript

Visibility

public

Author

claragabrii

Created

2026-05-08T15:58:53.61883Z

Updated

2026-05-14T23:03:58.864685Z

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

class LinkedList {
    constructor(value) {
        this.head = {
            value: value,
            next: null
        };
        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;
        }
        console.log(array)
        return array;
    }
    
    insert(index, value) {
        if(index >= this.length) {
            return this.append(value)
        }
        
        const newNode = new Node(value);
        
        const leader = this.traverseToIndex(index-1);
        
        const holdingPointer = leader.next;
        
        leader.next = newNode;
        newNode.next = holdingPointer;
        this.length++;
        return this.printList();
        
        
    }
    
     
    traverseToIndex(index) { 
        let counter = 0; 
        let currentNode = this.head;
        while(counter !== index) {
            currentNode = currentNode.next;
            counter++;
        }
        return currentNode;
    }
}

const myLinkedList = new LinkedList(10);
myLinkedList.append(5)
myLinkedList.append(16)
myLinkedList.append(8)
myLinkedList.prepend(2)
myLinkedList.printList()
myLinkedList.insert(2, 8)
myLinkedList.insert(5, 18)
INFO