diff --git a/Data Structures/doublyLinkedList.js b/Data Structures/doublyLinkedList.js new file mode 100644 index 0000000..2e86295 --- /dev/null +++ b/Data Structures/doublyLinkedList.js @@ -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 +};