diff --git a/src/_DataStructures_/LinkedList/index.js b/src/_DataStructures_/LinkedList/index.js index e7964c01..3406b602 100644 --- a/src/_DataStructures_/LinkedList/index.js +++ b/src/_DataStructures_/LinkedList/index.js @@ -125,8 +125,11 @@ class LinkedList { if (!this.head) { return null; } + if (index === 0) { + return this.removeFromBeginning(); + } - if (index >= this.length()) { + if (index >= this.size - 1) { return this.removeFromEnd(); } @@ -134,15 +137,15 @@ class LinkedList { let previous = address; let count = index; - while (count) { - address = address.next; + while (count >= 1) { previous = address; + address = address.next; count -= 1; } - const node = address; - previous.next = address.next.next; + previous.next = address.next; this.size -= 1; + node.next = null; return node; } @@ -156,6 +159,30 @@ class LinkedList { this.tail = this.head; this.size = 0; } + + traverseList() { + const arr = []; + let node = this.head; + while (node !== null) { + arr.push(node.data); + node = node.next; + } + return arr; + } } +// const ll = new LinkedList(); +// ll.addAtBeginning(20); +// ll.addAtBeginning(15); +// ll.addAtBeginning(10); +// ll.addAtBeginning(5); + +// console.log(ll.traverseList()); + +// console.log(ll.removeAt(0)); +// console.log(ll.traverseList()); + +// console.log(ll.removeAt(1)); +// console.log(ll.traverseList()); + module.exports = { LinkedList, Node };