Master advanced linked list operations including searching, insertion, and deletion. Learn efficient techniques for manipulating linked data structures.
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.length = 0;
}
search(value) {
let current = this.head;
while (current) {
if (current.value === value) {
return current;
}
current = current.next;
}
return null;
}
insert(value, index) {
if (index < 0 || index > this.length) {
return false;
}
const newNode = new Node(value);
if (index === 0) {
newNode.next = this.head;
this.head = newNode;
} else {
let current = this.head;
for (let i = 0; i < index - 1; i++) {
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
}
this.length++;
return true;
}
delete(index) {
if (index < 0 || index >= this.length) {
return null;
}
let deletedNode;
if (index === 0) {
deletedNode = this.head;
this.head = this.head.next;
} else {
let current = this.head;
for (let i = 0; i < index - 1; i++) {
current = current.next;
}
deletedNode = current.next;
current.next = current.next.next;
}
this.length--;
return deletedNode.value;
}
}
const list = new LinkedList();
// Insert elements
list.insert(10, 0); // [10]
list.insert(20, 1); // [10, 20]
list.insert(15, 1); // [10, 15, 20]
// Search for element
console.log(list.search(15)); // Node { value: 15, next: Node }
// Delete element
console.log(list.delete(1)); // 15
// List is now [10, 20]
Implement a method to search for a value starting from the end of the linked list.
Implement a method to insert multiple values at a specified position.
Implement a method to delete all nodes with a specific value.
Note: Previously, this course referenced the CodeSignal Arcade for practice, which is no longer available. The LeetCode problems below follow the same principles and are excellent for practicing linked list operations.