LinkedList Implementation

·

1 min read

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 
append(value){
  const node = new Node(value);
  // append tail pointer to this node
  this.tail.next = node
  this.tail = node
  this.length++
  return this
}

  // prepend
  prepend(value){
    const node = new Node(value);
    // append tail pointer to this node
    node.next = this.head
    this.head = node
    this.length++
  }


  // show the list
printList(){
  const array = [];
  let currentNode = this.head
  while(currentNode !== null){
    array.push(currentNode.value)
    currentNode = currentNode.next
  }
  return array
}

  //  insert at any point
  insert(index , value){
    // conditions
    if(index >= this.length){
      console.log('index bhadi hai bhai')
      return this.append(value)
    }
    const node = new Node(value)
      const leaderNode = this.traverseNode(index - 1);
      const holdingPointer = leaderNode.next
      leaderNode.next = node
      node.next = holdingPointer
      this.length++
      return this.printList()
  }
  remove(index){
    const leader = this.traverseNode(index - 1);
    const unwantedNode = leader.next
    leader.next = unwantedNode.next
    this.length--
  }

  traverseNode(index){
    let counter = 0;
    let currentNode = this.head
    while(counter !== index){
      currentNode = currentNode.next
      counter++
    }
    return currentNode
  }



}

const listt = new LinkedList(23)
listt.append(34)
listt.append(44)
listt.append(54)
listt.prepend(104)
listt.prepend(404)
listt.prepend(504)
listt.insert(2, 65428)
console.log(listt.printList())

Implementation LinkedList in Javascript