Quick actions

cmd+k|ctrl+k

Navigation

Languages

Implementation of Linked List

Snippet info

Language

JavaScript

Visibility

public

Author

dhamankovachi1

Created

2023-11-01T03:15:11.347382Z

Updated

2023-11-02T02:00:21.414113Z

class LinkedList{
    constructor(value){
        this.head={
            value:value,
            next:null,
        }
        this.tail=this.head
        this.length=1
    }
    
    append(value){
        const newNode={
            value:value,
            next:null
        };
        this.tail.next=newNode;
        this.tail=newNode;
        this.length++;
        return this;
    }
    
    prepend(value){
        const newNode={
            value:value,
            next:null,
        };
        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)
        }
        if(index===0){
            return this.prepend(value)
        }
        const newNode={
            value:value,
            next:null,
        };
        const leader=this.traverseIndex(index-1)
        const holdingPointer=leader.next;
        leader.next=newNode;
        newNode.next=holdingPointer;
        this.length++;
        return this.printList
    }
    
    traverseIndex(index){
        let counter=0;
        let currentNode=this.head;
        while(counter!=index){
            currentNode=currentNode.next;
            counter++;
        }
        return currentNode
    }
    
    remove(index){
        const leader=this.traverseIndex(index-1);
        const unWantedNode=leader.next;
        leader.next=unWantedNode.next;
        this.length--;
        return this.printList()
        
    }
}

const myLinkedList=new LinkedList(10)
myLinkedList.append(3)
myLinkedList.append(16)
myLinkedList.prepend(4)
myLinkedList.prepend(69)
myLinkedList.insert(1,45)
myLinkedList.insert(1,23)
myLinkedList.remove(2)
myLinkedList.remove(2)
myLinkedList.remove(0)
INFO