Quick actions

cmd+k|ctrl+k

Navigation

Languages

Linked List

Snippet info

Language

JavaScript

Visibility

public

Author

kishorrathva8298

Created

2022-04-03T00:10:26.003631Z

Updated

2022-04-08T07:16:45.482967Z

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

  append(value) {
    // O(1)
    const newNode = new Node(value);
    this.tail.next = newNode;
    this.tail = newNode;
    this.length++;
  }

  prepend(value) {
    // O(1)
    const newNode = new Node(value);
    newNode.next = this.head;
    this.head = newNode;
    this.length++;
  }

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

    return array;
  }

  insert(index, value) {
    if (index === 0) {
      return this.prepend(value);
    }
    if (index >= this.length) {
      return this.append(value);
    }
    let count = 0;
    let prev = this.head;
    const newNode = new Node(value);
    while (prev.next !== null) {
      if (count === index - 1) {
        newNode.next = prev.next;
        prev.next = newNode;
        this.length++;
        break;
      }
      prev = prev.next;
      count++;
    }
  }

  remove(index) {
    if (index === 0) {
      const newHead = this.head.next;
      delete this.head;
      this.head = newHead;
      return;
    }
    let count = 0;
    let prev = this.head;
    while (prev.next !== null) {
      if (count === index - 1) {
        const deleteThis = prev.next;
        delete prev.next;
        prev.next = deleteThis.next;
        this.length--;
        break;
      }
      prev = prev.next;
      count++;
    }
  }
  
reverse() {
    let prev = null;
    let currentNode = this.head;
    while (currentNode !== null) {
      const next = currentNode.next;
      currentNode.next = prev;
      prev = currentNode;
      currentNode = next;
    }
    this.head = prev;
   return this.printList(); 
  }
}

const myLinkedList = new LinkedList(10);
myLinkedList.append(50);
myLinkedList.append(60);
myLinkedList.append(70);
myLinkedList.append(80);
myLinkedList.prepend(1);
myLinkedList.insert(10, 99);
myLinkedList.remove(0);
console.log(myLinkedList.printList());
console.log(myLinkedList.reverse())
INFO