Here is the code I have gathered and worked on so far. I can't seem to get my remove function to work correctly. It keeps saying "Cannot read properties of undefined (reading 'value') when I try to execute it on the last two lines. Any tips or help would be appreciated, thank you!
function LinkedList() {
this.head = null;
this.tail = null;
this.length = 0;
}
function Node(value) {
this.value = value;
this.next = null;
}
// adds a node to the specified index
// if index is specified, accepts parameter (value, index)
// if no index is specified then add element to the end of list
LinkedList.prototype.add = function(...value) {
if (!this.head) {
this.head = this.tail = new Node(...value);
this.length++;
return;
}
while (value.length) {
let curr = value.pop();
this.tail.next = new Node(curr);
this.tail = this.tail.next;
this.length++;
}
}
// retrieves the node at the specified index
LinkedList.prototype.get = function(index) {
if (index >= this.length) {
return -1;
}
if (index === 0) {
return this.head;
}
let previousNode = null;
let currentNode = this.head;
for (let i = 0; i < index; i++) {
if (!currentNode.next) {
break;
}
previousNode = currentNode;
currentNode = currentNode.next;
}
previousNode.next = currentNode.next;
this.length--;
return currentNode;
}
// retrieves and removes the node at the specified index
// if no index is specified, removes the last node (tail)
LinkedList.prototype.remove = function(index) {
if (this.length === 0) {
return undefined;
}
if (this.head.value === index) {
this.removeFromHead();
return this;
}
let previousNode = this.head;
let thisNode = previousNode.next;
while (thisNode) {
if (thisNode.value === index) {
break;
}
previousNode = thisNode;
thisNode = thisNode.next;
}
if (thisNode === null) {
return undefined;
}
previousNode.next = thisNode.next;
this.length--;
return this;
}
LinkedList.prototype.removeFromHead = function() {
if (this.length === 0) {
return undefined;
}
const value = this.head.value;
this.head = this.head.next;
this.length--;
return value;
}
let linkedList = new LinkedList()
linkedList.add(0);
linkedList.add(1, 0);
linkedList
console.log(linkedList.remove().value) //should return 1
console.log(linkedList.remove().value) //should return 2
I'm not all cuteseed up