function LinkedList() {
this.head = null;
this.tail = null;
}
function Node(value) {
this.value = value;
this.next = null;
}
LinkedList.prototype.contains = function(value) {
if (!this.head || !this.tail) return false;
let node = this.head;
while (node) {
if (node.value === value) return true;
node = node.next;
}
return false;
};
LinkedList.prototype.indexOf = function() {
};
LinkedList.prototype.addToHead = function(value) {
const node = new Node(value);
if (!this.head && !this.tail) {
this.head = this.tail = node;
} else {
node.next = this.head;
this.head = node;
}
};
LinkedList.prototype.addToTail = function (value){
const node = new Node(value);
if (!this.head && !this.tail) {
this.head = this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
};
LinkedList.prototype.insertAfter = function(target, value) {
if (!this.head || !this.tail) return false;
let node = this.head;
const newNode = new Node(value);
while (node) {
if (node === target) {
newNode.next = node.next;
node.next = newNode;
}
node = node.next;
}
};
LinkedList.prototype.getValues = function(){
const values = [];
let node = this.head;
while (node) {
values.push(node.value)
node = node.next;
}
return values;
};
LinkedList.prototype.iterativeReverse = function(){
let current = this.head;
let prev = null;
let next = null;
this.head = this.tail;
this.tail = current;
while (current) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
return this.tail;
};
LinkedList.prototype.recursiveReverse = function(){
const current = arguments[0] !== undefined ? arguments[0] : this.head;
const prev = arguments[1] !== undefined ? arguments[1] : null;
if (!current) {
let temp = this.head;
this.head = this.tail;
this.tail = temp;
return this.head;
}
const next = current.next;
current.next = prev;
this.recursiveReverse(next, current)
};