Quick actions

cmd+k|ctrl+k

Navigation

Languages

linked list

Snippet info

Language

JavaScript

Visibility

public

Author

pranaypandey730

Created

2020-02-27T01:19:34Z

Updated

2020-02-27T22:19:23Z

class LinkedList {
  constructor(value){
    this.head = {
      value: value,
      next: null
    };
    this.tail = this.head;
    this.length = 1;

  }



// append  here a new element in the linked list
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.next !== null){
        array.push(currentNode.value);
        currentNode = currentNode.next;
    }
    
    return array;
    
}
insert(index, value){
    
    const newNode = {
        value: value,
        next: null
        
    };
    if(index >= this.length){
        this.append(value);
        this.length++;
    }
    if(index === 0){
        this.prepend(value);
        this.length++;
    }
    
    
    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(20);
myLinkedList.append(30);
myLinkedList.append(40);
myLinkedList.prepend(30);
myLinkedList.insert(44, 99);
console.log(myLinkedList.printList());
// console.log(myLinkedList);
INFO