Quick actions

cmd+k|ctrl+k

Navigation

Languages

LinkedList

Snippet info

Language

JavaScript

Visibility

public

Author

ivan.burychka

Created

2020-10-10T06:25:41Z

Updated

2020-10-10T10:47:34Z

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


class LinkedList {
    constructor(value) {
        this.head = new Node(value);
        this.tail = this.head;
        this.length = 1;
    }
    
    uppend(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;
    }
    
    insert(index, value) {
        const newNode = new Node(99);
        if(index === 0) {
            this.prepend(value);
        } else if (index >= this.length) {
            this.uppend(value)
        } else {
            let i = 0;
            let currentNode = this.head;
            while(i < index - 1) {
                currentNode = currentNode.next;
                i++
            }
            
           // currentNode.next = newNode;
            newNode.next = currentNode.next;
            currentNode.next = newNode;
        }
        return this;
        
    }
    
    printList() {
        const values = [this.head.value];
        let currentNode = this.head;
        while (currentNode.next) {
            currentNode = currentNode.next;
            values.push(currentNode.value);
        }
        console.log(values);
    }


}

const myList = new LinkedList(5);
myList.uppend(10);
myList.uppend(15);
myList.prepend(60);
myList.prepend(30);
myList.insert(1, 99);
myList.printList();

INFO