Visualize common Singly Linked List operations.
Add nodes or perform operations on the linked list.
A singly linked list is a linear data structure where elements are not stored at contiguous memory locations. Instead, elements are linked using pointers.
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
// Add to head - O(1)
addHead(data) {
const newNode = new Node(data);
newNode.next = this.head;
this.head = newNode;
}
// Add to tail - O(n)
addTail(data) {
const newNode = new Node(data);
if (!this.head) {
this.head = newNode;
return;
}
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
// Delete node by value - O(n)
delete(data) {
if (!this.head) return false;
if (this.head.data === data) {
this.head = this.head.next;
return true;
}
let current = this.head;
while (current.next && current.next.data !== data) {
current = current.next;
}
if (current.next) { // Found the node before the one to delete
current.next = current.next.next;
return true;
}
return false; // Not found
}
// Search for value - O(n)
search(data) {
let current = this.head;
while (current) {
if (current.data === data) {
return current; // Return the node if found
}
current = current.next;
}
return null; // Not found
}
}