Data Structures: Remove Elements from a Linked List by Index
This commit is contained in:
parent
a78aa11881
commit
04e2571121
62
Data Structures/linkedListClassRemoveByIndex.js
Normal file
62
Data Structures/linkedListClassRemoveByIndex.js
Normal file
@ -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
|
||||
}
|
Loading…
Reference in New Issue
Block a user