From 04e2571121bd2c140c051363c733d26a9a1f08bb Mon Sep 17 00:00:00 2001 From: Manish Date: Fri, 25 Aug 2023 11:26:55 +1000 Subject: [PATCH] Data Structures: Remove Elements from a Linked List by Index --- .../linkedListClassRemoveByIndex.js | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Data Structures/linkedListClassRemoveByIndex.js diff --git a/Data Structures/linkedListClassRemoveByIndex.js b/Data Structures/linkedListClassRemoveByIndex.js new file mode 100644 index 0000000..7eb7bb1 --- /dev/null +++ b/Data Structures/linkedListClassRemoveByIndex.js @@ -0,0 +1,62 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/remove-elements-from-a-linked-list-by-index + +function LinkedList() { + var length = 0; + var head = null; + + var Node = function (element) { + this.element = element; + this.next = null; + }; + + this.size = function () { + return length; + }; + + this.head = function () { + return head; + }; + + this.add = function (element) { + var node = new Node(element); + if (head === null) { + head = node; + } else { + var currentNode = head; + + while (currentNode.next) { + currentNode = currentNode.next; + } + + currentNode.next = node; + } + + length++; + }; + + // Only change code below this line + this.removeAt = (index) => { + if (index < 0 || index >= length || head === null) { + return null; + } + let i = 0; + let previousNode = null; + let currentNode = head; + while (i < index && currentNode !== null) { + i++; + previousNode = currentNode; + currentNode = currentNode.next; + } + if (currentNode === null) { + return null; + } + if (previousNode === null) { + head = currentNode.next; + } else { + previousNode.next = currentNode.next; + } + length--; + return currentNode.element; + }; + // Only change code above this line +}