Linked List Data Structure Code in JavaScript

In the examples below we show how to implement Linked List Data Structure in Javascript


class Node {
    constructor(data, next=null)
         this.data = data;
         this.next = next; 
    }
}
class LinkedList {
     constructor(data) {
         this.head = null;
     }
     ///////////
     insertStart(data) {
        this.head = new Node(data, this.head);
     } 
     ///////////
     size() {
       let cnt = 0;
       let node = this.head;
       while(node) {
           cnt++;
            node = node.next;
       }
       return cnt; 
    }
   ///////////
    getAt(index) {
        if (index == 0) {
             return this.head;
        }
         let cnt == 0;
         let node = this.head;
          while(node) {
             if (cnt == index) {
                 return node;
             }
              cnt++; 
              node = node.next; 
          }
          return null; 
     }
   ///////////
   removeLast() {
    if (!this.head) {
      return;
    }
    if (!this.head.next) {
      this.head = null;
      return;
    }
    let previous = this.head;
    let node = this.head.next;
    while (node.next) {
      previous = node;
      node = node.next;
    }
    previous.next = null;
  }
}
///test
const l = new LinkedList();
l.insertStart('a');
console.log(l.size());
console.log(l.head.data);
    
   

Leave a Reply

Your email address will not be published. Required fields are marked *