48 lines
1.2 KiB
JavaScript
48 lines
1.2 KiB
JavaScript
|
// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/create-a-doubly-linked-list
|
||
|
|
||
|
var Node = function (data, prev) {
|
||
|
this.data = data;
|
||
|
this.prev = prev;
|
||
|
this.next = null;
|
||
|
};
|
||
|
var DoublyLinkedList = function () {
|
||
|
this.head = null;
|
||
|
this.tail = null;
|
||
|
// Only change code below this line
|
||
|
this.add = (element) => {
|
||
|
const node = new Node(element, this.tail);
|
||
|
if (this.head === null) {
|
||
|
this.head = node;
|
||
|
this.tail = node;
|
||
|
} else {
|
||
|
this.tail.next = node;
|
||
|
this.tail = node;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
this.remove = (element) => {
|
||
|
let prevNode = null;
|
||
|
let currentNode = this.head;
|
||
|
while (currentNode !== null && currentNode.data !== element) {
|
||
|
prevNode = currentNode;
|
||
|
currentNode = currentNode.next;
|
||
|
}
|
||
|
if (currentNode === null || currentNode.data !== element) {
|
||
|
return;
|
||
|
}
|
||
|
if (prevNode === null) {
|
||
|
this.head = currentNode.next;
|
||
|
} else {
|
||
|
prevNode.next = currentNode.next;
|
||
|
}
|
||
|
if (currentNode.next === null) {
|
||
|
this.tail = prevNode;
|
||
|
} else {
|
||
|
const nextNode = currentNode.next;
|
||
|
nextNode.prev = prevNode;
|
||
|
}
|
||
|
return currentNode.element;
|
||
|
};
|
||
|
// Only change code above this line
|
||
|
};
|