Linked List

ZeeshanAli-0704 - Sep 4 '22 - - Dev Community
class Node {
  constructor(data, next = null) {
    this.data = data;
    this.next = next;
  }
}

class linkedList {
  constructor(head = null) {
    this.head = head;
    this.size = 0;
  }

  insertAtFirst(data) {
    this.head = new Node(data, this.head);
    this.size++;
  }
  insertAtLast(data) {
    if (this.head === null) {
      this.head = new Node(data);
    } else {
      let current = this.head;
      while (current.next) {
        current = current.next;
      }
      current.next = new Node(data);
    }
    this.size++;
  }
  insertAtIndex(data, index) {
    if (index > 0 && index > this.size) {
      return;
    }

    if (index === 0) {
      insertAtFirst(data);
      return;
    }

    const node = new Node(data);
    let count = 0;
    let previous, next;
    let current = this.head;

    while (count < index) {
      count++;
      previous = current;
      current = current.next;
    }
    node.next = current;
    previous.next = node;

    this.size++;
  }

  getAt(index) {
    let current = this.head;
    let count = 0;

    while (current) {
      if (count == index) {
        console.log(current.data);
      }
      count++;
      current = current.next;
    }

    return null;
  }

  removeAt(index) {
    if (index > 0 && index > this.size) {
      return;
    }

    let current = this.head;
    let previous;
    let count = 0;

    // Remove first
    if (index === 0) {
      this.head = current.next;
    } else {
      while (count < index) {
        count++;
        previous = current;
        current = current.next;
      }

      previous.next = current.next;
    }

    this.size--;
  }
  clearList() {
    this.head = null;
    this.size = 0;
  }

  print() {
    let current = this.head;

    while (current) {
      console.log(current.data);
      current = current.next;
    }
  }
}

let ll = new linkedList();

ll.insertAtFirst(100);
ll.insertAtFirst(200);
ll.insertAtFirst(300);
ll.insertAtLast(400);
ll.insertAtIndex(500, 3);
ll.getAt(3);
ll.removeAt(1);

ll.print();

Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .