Quick actions

cmd+k|ctrl+k

Navigation

Languages

SinglyLinkedList

Snippet info

Language

JavaScript

Visibility

public

Author

vinnysantos559

Created

2019-10-29T22:19:42Z

Updated

2019-10-31T03:01:16Z

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;
    }
    
    printList() {
        const array = [];
        
        let currentNode = this.head;
        while( currentNode !== null ) {
            array.push(currentNode.value);
            currentNode = currentNode.next;
        }
        
        return array;
    }
    
    prepend(value) {
        const newNode = new Node(value);
        newNode.next = this.head;
        this.head = newNode;
        this.length++;
    }
    
    append(value) {
        const newNode = new Node(value);
        this.tail.next = newNode;
        this.tail = newNode;
        this.length++;
    }
    
    insert(value, index) {
        if(index >= this.length) {
            return this.append(value);
        }
        
        const newNode = new Node(value);
        let leader = this._traverseToIndex(index - 1);
        newNode.next = leader.next;
        leader.next = newNode;
        this.length++;
    }
    
    remove(index) {
        if( index >= this.length || index < 0) {
            return 'out of bounds index';
        }
        
        if( index === 0 ) {
            this.head = this.head.next;
        }
        
        else {
            let leader = this._traverseToIndex(index -1);
            let unwantedNode = leader.next;
            leader.next = unwantedNode.next;
        }
        this.length--;
    }
    
    reverse() {
        if( linkedList.length <= 1) {
            return linkedList;
        }
        
        let prevNode = this.head;
        let currentNode = this.head.next;
        let nextNode = currentNode.next;
        prevNode.next = null;
        currentNode.next = prevNode;
        while( nextNode !== null ) {
            prevNode = currentNode;
            currentNode = nextNode;
            nextNode = nextNode.next;
            currentNode.next = prevNode;
        }
        
        let newTail = this.head;
        this.head = currentNode;
        this.tail = newTail;
    }
    
    _traverseToIndex(index){
        let counter = 0;
        let currentNode = this.head;
        
        while( counter < index ) {
            currentNode = currentNode.next;
            counter++;
        }
        
        return currentNode;
    }
}

const linkedList = new LinkedList(5);
linkedList.prepend(4)
linkedList.append(8);
linkedList.insert(6,3)
linkedList.append(17);
linkedList.remove(1);
linkedList.reverse();
console.log(linkedList.printList())
INFO