plastikaweb
12/11/2017 - 2:29 PM

Linked List data structure by plastikaweb - https://repl.it/@plastikaweb/LightblueTomatoRaven

Linked List data structure by plastikaweb - https://repl.it/@plastikaweb/LightblueTomatoRaven

const es6 = require('es6');
function LinkedList() {
  this.head = null;
  this.tail = null;
}

LinkedList.prototype.addToHead = value => {
  const newNode = new Node(value, this.head, null);
  if (this.head) {
    this.head.prev = newNode;
  } else {
    this.tail = newNode;
  }
  this.head = newNode;
};

LinkedList.prototype.addToTail = value => {
  const newNode = new Node(value, null, this.tail);
  if (this.tail) {
    this.tail.next = newNode;
  } else {
    this.head = newNode;
  }
  this.tail = newNode;
};

LinkedList.prototype.removeHead = () => {
  if (!this.head) return null;
  const val = this.head.value;
  this.head = this.head.next;
  if (this.head) {
    this.head.prev = null;
  } else {
    this.tail = null;
  }
  return val;
};

LinkedList.prototype.removeTail = () => {
  if (!this.tail) return null;
  const val = this.tail.value;
  this.tail = this.tail.prev;
  if (this.tail) {
    this.tail.next = null;
  } else {
    this.head = null;
  }
  return val;
};

LinkedList.prototype.search = (searchValue) => {
  let currentNode = this.head;
  while(currentNode) {
    if (currentNode.value === searchValue) {
      return currentNode.value;
    }
    currentNode = currentNode.next;
  }
  return null;
}

LinkedList.prototype.indexOf = (value) => {
  let currentNode = this.head;
  const indexes = [];
  let index = 0;
  while(currentNode) {
    if (currentNode.value === value) {
      indexes.push(index);
    }
    currentNode = currentNode.next;
    index++;
  }
  return indexes;
};

function Node(value, next, prev) {
  this.value = value;
  this.next = next;
  this.prev = prev;
}

const LL = new LinkedList();

LL.addToHead('one');
LL.addToHead('two');
LL.addToHead('three');
LL.addToHead('two');

console.log(LL.indexOf('two'));