Linked List
Example
Implementation
class Node<T> {
data: T;
next: Node<T> | null;
constructor(data: T, next: Node<T> | null = null) {
this.data = data;
this.next = next;
}
}
class LinkedList<T> {
head: Node<T> | null = null;
tail: Node<T> | null = null;
size = 0;
add(data: T) {
const newNode = new Node(data);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail!.next = newNode;
this.tail = newNode;
}
this.size++;
}
remove(data: T) {
if (!this.head) {
return;
}
if (this.head.data === data) {
this.head = this.head.next;
this.size--;
return;
}
let current = this.head;
while (current.next) {
if (current.next.data === data) {
current.next = current.next.next;
if (!current.next) {
this.tail = current;
}
this.size--;
return;
}
current = current.next;
}
}
print() {
let current = this.head;
while (current) {
console.log(current.data);
current = current.next;
}
}
}Usage
Last updated