Data Structures: Create a Doubly Linked List
This commit is contained in:
parent
d0006d7064
commit
44f36ee920
47
Data Structures/doublyLinkedList.js
Normal file
47
Data Structures/doublyLinkedList.js
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
// 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
|
||||||
|
};
|
Loading…
Reference in New Issue
Block a user