From 3ad57243a2c00e4254ea94be4002d3acff6309f5 Mon Sep 17 00:00:00 2001 From: Avijit Das Date: Sun, 13 Oct 2019 21:22:24 +0530 Subject: [PATCH] fixed removeAt function --- src/_DataStructures_/LinkedList/index.js | 36 +++++++++--------------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/src/_DataStructures_/LinkedList/index.js b/src/_DataStructures_/LinkedList/index.js index e7964c01..8c3abb06 100644 --- a/src/_DataStructures_/LinkedList/index.js +++ b/src/_DataStructures_/LinkedList/index.js @@ -123,28 +123,20 @@ class LinkedList { removeAt(index) { if (!this.head) { - return null; - } - - if (index >= this.length()) { - return this.removeFromEnd(); - } - - let address = this.head; - let previous = address; - let count = index; - - while (count) { - address = address.next; - previous = address; - count -= 1; - } - - const node = address; - previous.next = address.next.next; - this.size -= 1; - node.next = null; - return node; + return null; + } + if (index === 0) { + this.head = this.head.next; + return; + } + const previous = this.getAt(index - 1); + + if (!previous || !previous.next) { + return; + } + + previous.next = previous.next.next; + return this.head } length() {