Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 32 additions & 5 deletions src/_DataStructures_/LinkedList/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,24 +125,27 @@ 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();
}

let address = this.head;
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;
}
Expand All @@ -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 };